我需要一個包含多種類型的抽象切片。最簡化的代碼是這樣的:package mainimport "fmt"type A interface{}type X stringfunc main() { sliceA := make([]A, 0, 0) sliceX := []X{"x1", "x2"} var appendedSlice []A appendedSlice = append(sliceA, sliceX[0], sliceX[1]) // (1) works appendedSlice = append(sliceA, sliceX...) // (2) doesn't work fmt.Println(appendedSlice)}在我的真實程序中,接口A定義了一些功能,X和其他類型也實現(xiàn)了它。第 (2) 行引發(fā)錯誤cannot use sliceX (type []X) as type []A in append。我認為 (2) 是 (1) 的語法糖,但我可能遺漏了一些東西……我是否必須始終將元素 X 一個一個地添加到切片 A 中?提前謝謝你們!
1 回答

撒科打諢
TA貢獻1934條經(jīng)驗 獲得超2個贊
問題是interface{}和string是兩種不同的類型。要將切片從 轉(zhuǎn)換string為interface{}您必須通過以下方式之一進行:
創(chuàng)建 sliceA 并將其大小初始化為 sliceX 長度
sliceA := make([]A, len(sliceX))
for ix, item := range sliceX {
? ? sliceA[ix] = item
}
動態(tài)地將 sliceX 項附加到 appendedSlice
var appendedSlice []A
for ix := range sliceX {
? ? appendedSlice = append(appendedSlice, sliceX[ix])
}
- 1 回答
- 0 關(guān)注
- 116 瀏覽
添加回答
舉報
0/150
提交
取消