Go:在结构中声明一个切片?
Go: declaring a slice inside a struct?
我有以下代码:
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 }
我做错了什么?
谢谢!
您可以在结构声明中声明一个切片,但不能对其进行初始化。你必须通过不同的方式来做到这一点。
// 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,
}
}
首先,您不能 assign/initialize 在结构内部。 := 运算符声明和分配。但是,您可以简单地获得相同的结果。
这是一个简单、琐碎的示例,大致可以完成您正在尝试的操作:
type house struct {
s []string
}
func main() {
h := house{}
a := make([]string, 3)
h.s = a
}
我从来没有这样写过,但如果它符合你的目的......它无论如何都能编译。
我有以下代码:
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 }
我做错了什么?
谢谢!
您可以在结构声明中声明一个切片,但不能对其进行初始化。你必须通过不同的方式来做到这一点。
// 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,
}
}
首先,您不能 assign/initialize 在结构内部。 := 运算符声明和分配。但是,您可以简单地获得相同的结果。
这是一个简单、琐碎的示例,大致可以完成您正在尝试的操作:
type house struct {
s []string
}
func main() {
h := house{}
a := make([]string, 3)
h.s = a
}
我从来没有这样写过,但如果它符合你的目的......它无论如何都能编译。