切片的(整数)索引作为结构数组

时间:2018-12-19 15:03:00

标签: arrays dictionary go slice

在Go create array中,数组的每个元素将是切片还是结构的数组,是否可能。

类似于PHP

    $a = [1=>"test", 2=>""]
    // in this example 2 is integer will be for GoLang?
    $a[2] = [ object, object, object ]

我可以在Go中执行类似的操作吗?我知道语法错误。

   var a [int][]StructureName

   b := make([]StructureName, 0)
   b := append ( b, StructureName{a, b, c, d})
   b := append ( b, StructureName{e, f, g, h})

   a[0] = append (a[0][0], b)

`/*
[
1 => [
    ‘username1’, <-- string element
    ‘events’=>[ <-- array of structures
        object1, <-- structure
        object2, <-- structure
        object3 <-- structure
        ]
    ],
2 => [ <-- next record
    ‘username2’,
    ‘events’=>[
        object1,
        object2,
        object3
        ]
    ]
]
*/
`

2 个答案:

答案 0 :(得分:2)

声明与数据结构匹配的类型。这样可以确保类型安全,并避免在访问数据时键入断言。

在这种情况下,您似乎需要一片结构,其中的字段上也是一片事件结构。

type Event struct {
    // Even fields TBD
}

type User struct {
    Name string
    Events []*Event
}

var users []*User

users = append(users, &User{
    Name: "name1",
    Events: []*Event{ object1, object2, object3 },
})

答案 1 :(得分:0)

您可以使用map并通过int =>接口{}对其进行映射。

package main

import (
    "fmt"
)

func main() {
    m := make(map[int]interface{})
    var x []interface{}
    x = append(x, "username")
    x = append(x, []int{3, 1, 3})
    m[1] = x
    fmt.Println(m)
}

https://play.golang.org/p/B_dsvARic8c

希望这会有所帮助。