我有以下代码:
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/