【发布时间】:2018-09-03 12:50:37
【问题描述】:
我想初始化一个包含界面列表的地图,而不必一一添加:
type Pixel struct {
X float64
Y float64
}
type Vertex struct {
X float64
Y float64
Z float64
}
type testpair struct {
filename string
values []interface{}
}
var tests = map[string]testpair{
"test1": {
filename: "file1.csv",
values: []Pixel{
{X: 12.5, Y: 23.4},
{X: 17.2, Y: 7.9},
}
},
"test2": {
filename: "file2.csv",
values: []Vertex{
{X: 10.7, Y: 13.3, Z: 25.1},
{X: 18.3, Y: 16.9, Z: 16.4},
}
},
}
编译器会输出这样的错误:
不能在字段值中使用 []Pixel 字面量(类型 []Pixel)作为类型 []interface {}
如果我将 []interface{} 切换为 []Pixel,我可以初始化地图,但我只能使用唯一类型的 Pixel 或 Vertex。
有没有办法强制编译器接受具有特定结构的数组初始化,同时将其声明为接口数组?
【问题讨论】:
-
将
[]Pixel{ {X:...}, {X:...}}替换为:[]interface{}{ Pixel{X:...}, Pixel{X:...}}。
标签: go