英文:
golang initialize a slice of empty interfaces
问题
我定义了一个结构体:
type container struct {
Data []interface{}
}
我希望将各种不同数据类型的切片分配给它。例如:
ints := []int{2, 3, 4}
tmp := container{ints}
然而,编译器报错:
无法将 ints(类型为 []int)作为字段值中的 []interface{} 类型使用
我应该如何定义 container 结构体?或者分配需要以不同的方式进行?
可以在这里找到一个完整的示例。
英文:
I defined a struct
type container struct{
Data []interface{}
}
and was hoping to assign slice of all different kinds of data types to it. For example
ints := []int{2,3,4}
tmp := container{ints}
However, the compiler complains:
> cannot use ints (type []int) as type []interface {} in field value
How should I define the container struct? Or the assignment needs to be done differently?
A complete example can be found here
答案1
得分: 3
问题在于,即使每个结构体实现了各自的接口,结构体数组也不能被用作接口数组。你需要直接追加每个元素,像这样:
package main
import (
"fmt"
)
type a struct{
Data []interface{}
}
func main() {
ints := []int{2,3,4}
tmp := a{}
for _, v := range ints {
tmp.Data = append(tmp.Data, v)
}
fmt.Println(ints, tmp) // [2 3 4] {[2 3 4]}
}
英文:
The issue is that an array of structs can't be used as an array of interfaces, even if the individual structs implement the individual interfaces. You would need to append each element directly like so:
package main
import (
"fmt"
)
type a struct{
Data []interface{}
}
func main() {
ints := []int{2,3,4}
tmp := a{}
for _, v := range ints {
tmp.Data = append(tmp.Data, v)
}
fmt.Println(ints, tmp) // [2 3 4] {[2 3 4]}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论