""] // in this example 2 is integer will be for golang? $a[2] = [ object, object, objec" />
登录
首页 >  Golang >  Go问答

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

来源:stackoverflow

时间:2024-04-06 11:24:37 244浏览 收藏

大家好,今天本人给大家带来文章《(整数)作为结构数组的切片索引》,文中内容主要涉及到,如果你对Golang方面的知识点感兴趣,那就请各位朋友继续看下去吧~希望能真正帮到你们,谢谢!

问题内容

go 中是否可以创建数组,其中数组的每个元素都是切片或结构数组。

类似 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
        ]
    ]
]
*/
`

解决方案


您可以使用map并从int => interface{}映射它。

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

希望这有帮助。

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

在这种情况下,看起来您需要一个结构体切片,其中一个字段也是一个事件结构体切片。

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 },
})

好了,本文到此结束,带大家了解了《(整数)作为结构数组的切片索引》,希望本文对你有所帮助!关注golang学习网公众号,给大家分享更多Golang知识!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>