Go:在结构中声明一个 slice ?

标签 go struct slice

我有以下代码:

type room struct {
    width float32
    length float32
}
type house struct{
    s := make([]string, 3)
    name string
    roomSzSlice := make([]room, 3)
} 

func main() {


}

当我尝试构建和运行它时,出现以下错误:

c:\go\src\test\main.go:10: syntax error: unexpected :=
c:\go\src\test\main.go:11: non-declaration statement outside function body
c:\go\src\test\main.go:12: non-declaration statement outside function body
c:\go\src\test\main.go:13: syntax error: unexpected }

我做错了什么?

谢谢!

最佳答案

您可以在结构声明中声明一个 slice ,但不能对其进行初始化。你必须通过不同的方式来做到这一点。

// Keep in mind that lowercase identifiers are
// not exported and hence are inaccessible
type House struct {
    s []string
    name string
    rooms []room
}

// So you need accessors or getters as below, for example
func(h *House) Rooms()[]room{
    return h.rooms
}

// Since your fields are inaccessible, 
// you need to create a "constructor"
func NewHouse(name string) *House{
    return &House{
        name: name,
        s: make([]string, 3),
        rooms: make([]room, 3),
    }
}

请将以上内容视为 runnable example on Go Playground


编辑

要按照评论中的要求部分初始化结构,可以简单地更改

func NewHouse(name string) *House{
    return &House{
        name: name,
    }
}

请将以上内容视为 runnable example on Go Playground ,再次

关于Go:在结构中声明一个 slice ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36379502/

相关文章:

C - 将指针数据保存/加载到文件

javascript - 如何使用正则表达式或字符串函数在字符串中插入反斜杠以在 JavaScript 中提取子字符串?

go - 使用不带命令的 PTY

ember.js - 使用 emberJS 和 Handlebars 显示来自 promise 的 map

c# - 将 C# GRPC 客户端连接到 Go Server

python - 数据帧切片并旋转为多个数据帧

python - 在Python中对列表进行切片

google-app-engine - 如何在 App Engine flex 环境和 Go 上正确启用 HTTPS?

arrays - 在 Swift 中使用 NSCoding 归档可选结构数组?

pointers - 需要帮助通过 'reflect: NumField of non-struct type'