英文:
Create generic struct fields inside a struct and initial in go
问题
如何在Go中创建一个包含通用结构的结构体,并对其进行初始化?
我在这里看到了一个类似的问题https://stackoverflow.com/questions/68166558/generic-structs-with-go,但是字段是基本类型,我需要结构体的字段是通用类型,并将该字段设置为其他结构体。
我尝试了以下代码,但它不起作用:
type ResponseData[T struct{}] struct {
status int
error string
soaErrorCode string
soaErrorDesc string
clientMessageId string
path string
data T
}
我还尝试对其进行初始化:
message := struct {
accountId string
}{
accountId: "0344561299",
}
bodyin := RoutinQueryInput[struct{}]{
Destination: "AAA-BBB",
Version: "1.2",
Message: message,
}
但是它报错:
无法将'type struct {...}'用作'type struct{}'
在Java中,我们可以在一个对象中创建通用对象,那么在Go中该如何实现呢?
英文:
How to create a struct with generic struct inside and init it in go ,
I see similar question here https://stackoverflow.com/questions/68166558/generic-structs-with-go but the fields is primitive type , I need the field of struct is generic and set this field as other struct
I try but it not work
type ResponseData[T struct{}] struct {
status int
error string
soaErrorCode string
soaErrorDesc string
clientMessageId string
path string
data T
}
And I try to init it
message := struct {
accountId string
}{
accountId: "0344561299",
}
bodyin := RoutinQueryInput[struct{}]{
Destination: "AAA-BBB",
Version: "1.2",
Message: message,
}
It said :
> Cannot use 'message' (type struct {...}) as the type struct{}
In Java, we can create object generic inside a object , how to do that in go?
答案1
得分: 4
如果你的类型参数列表写成[T struct{}]
,那意味着类型T
只能是struct{}
。这并不意味着它可以是任何结构体类型,而是字面上的struct{}
(空结构体)。
没有类型约束可以表示“所有的结构体类型”。即使有,也没有任何好处,因为它并没有描述任何共同的行为。
你应该将其改为type ResponseData[T any]
,这样data
字段可以是任何类型。
如果你将消息类型声明为命名类型,会更方便,这样你可以在实例化时引用它。例如:
type messageType struct {
accountId string
}
message := messageType{
accountId: "0344561299",
}
bodyin := RoutinQueryInput[messageType]{
Destination: "AAA-BBB",
Version: "1.2",
Message: message,
}
英文:
If your type parameter list says [T struct{}]
, that means type T
can only be struct{}
. That doesn't mean that it can be any struct type, it literally means struct{}
(the empty struct).
There's no type constraint that means "all types which are structs". Even if there was, it wouldn't do you any good, because it doesn't describe any common behaviour.
You should change it to be type ResponseData[T any]
so that the data
field can be of any type.
It will also be more convenient if you declare your message type as a named type, so you can reference it on instantiation. For example:
type messageType struct {
accountId string
}
message := messageType{
accountId: "0344561299",
}
bodyin := RoutinQueryInput[messageType]{
Destination: "AAA-BBB",
Version: "1.2",
Message: message,
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论