Go中的多维切片

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

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

    }

huangapple
  • 本文由 发表于 2014年1月12日 17:37:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/21073192.html
匿名

发表评论

匿名网友

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

确定