英文:
Multidimensional Slices in Go
问题
我想在Go语言中使用一个具有可变数量元素的数组/切片(在编译时不知道),并且能够动态添加不同类型的新元素,例如:
data[0] := "string"
data[1] // 切片
data[1][0] := "another string"
data[1][1] := 42 // 整数
这种情况是否可能?
英文:
I would like to have an array / slice in Go with a variadic number of elements (not known at compile time) and be able to dinamically add new elements of different types, for instance:
data[0] := "string"
data[1] // slice
data[1][0] := "another string"
data[1][1] := 42 // int
Is this possible somehow?
答案1
得分: 6
这是一个使用空接口interface{}
的方法,虽然有点丑陋,但是可行:
package main
import "fmt"
func main() {
variadic := []interface{}{}
variadic = append(variadic, "foo")
variadic = append(variadic, []interface{}{"bar", 42})
// 这将打印出"foo"
fmt.Println(variadic[0])
// 注意,在访问之前,你需要将variadic[1]转换为数组
fmt.Println(variadic[1].([]interface{})[0])
}
如果你允许每个元素都是一个长度可变的任意类型的数组,那么代码会稍微简洁一些:
package main
import "fmt"
func main() {
variadic := [][]interface{}{}
variadic = append(variadic, []interface{}{"foo"})
variadic = append(variadic, []interface{}{"bar", 42})
fmt.Println(variadic[0])
fmt.Println(variadic[1][0])
fmt.Println(variadic[1][1])
}
英文:
It's a bit ugly but possible using empty interfaces, interface{}
:
package main
import "fmt"
func main() {
variadic := []interface{}{}
variadic = append(variadic, "foo")
variadic = append(variadic, []interface{}{"bar", 42})
//this will print "foo"
fmt.Println(variadic[0])
//note that you have to cast variadic[1] to an array before accessing it
fmt.Println(variadic[1].([]interface{})[0])
}
If you allow the assumption that each element must be an array of anything with varying length, it's a bit less ugly:
package main
import "fmt"
func main() {
variadic := [][]interface{}{}
variadic = append(variadic, []interface{}{"foo"})
variadic = append(variadic, []interface{}{"bar", 42})
fmt.Println(variadic[0])
fmt.Println(variadic[1][0])
fmt.Println(variadic[1][1])
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论