英文:
declaring generic type object in go
问题
在Go语言中,没有像其他语言那样可以接受任何类型的通用类型Object。但是,你可以使用空接口interface{}来实现类似的功能。空接口可以接受任何类型的值作为其实参。在你的代码中,你可以将data字段的类型定义为interface{},以接受任何类型的有效载荷。
以下是修改后的代码示例:
type Foo struct {
data interface{}
}
这样,你就可以将任何类型的值分配给data字段了。请注意,使用空接口会失去类型安全性,因此在使用时需要小心处理类型转换和类型断言。
英文:
Is there a generic type Object in golang similar to other languages that can be assigned any kind of payload?
type Foo struct {
data object
}
答案1
得分: 14
所有的Go类型都实现了空接口interface{}。
type Foo struct {
data interface{}
}
空接口在《Go之旅》、《反射定律》和规范中有详细介绍。
英文:
All Go types implement the empty interface interface{}.
type Foo struct {
data interface{}
}
The empty interface is covered in A Tour of Go, The Laws of Reflection and the specification.
答案2
得分: 4
从Go 1.18开始,你可以使用any作为字段或变量的类型,它是interface{}的别名,看起来比interface{}更好。
type Foo struct {
data any
}
或者你也可以设计一个接受类型参数的结构体,这样它就变得真正通用了:
type Foo[T any] struct {
data T
}
用法:
foo := Foo[string]{data: "hello"}
主要区别在于,没有类型参数的Foo值可以使用==和!=与其他Foo值进行比较,并根据实际字段的值返回true或false。类型是相同的!对于interface{}/any字段,它将比较存储在其中的值。而Foo[T any]的实例则无法进行比较,会导致编译错误;因为使用不同的类型参数会产生完全不同的类型——Foo[string]和Foo[int]不是相同的类型。在这里可以查看示例 -> https://go.dev/play/p/zj-kC0VvlUH?v=gotip
英文:
Starting in Go 1.18 you can use any — alias of interface{} as type of field or variable. It looks better than interface{}.
type Foo struct {
data any
}
Or also you can design the struct as accepting a type parameter. This way it becomes truly generic:
type Foo[T any] struct {
data T
}
Usage:
foo := Foo[string]{data: "hello"}
The main difference is that Foo values without type parameter can be compared using == and != with other Foo values, and yield true or false based on the actual fields. The type is the same! — In case of interface{}/any fields, it will compare the values stored in there. Instances of Foo[T any] instead can NOT be compared with compilation error; because using different type parameters produces different types altogether — Foo[string] is not the same type as Foo[int]. Check it here -> https://go.dev/play/p/zj-kC0VvlUH?v=gotip
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论