golang initialize a slice of empty interfaces

huangapple go评论84阅读模式
英文:

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]}
}

huangapple
  • 本文由 发表于 2016年12月11日 09:19:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/41082059.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定