我有以下代码:
type room struct {
width float32
length float32
}
type house struct{
s := make([]string, 3)
name string
roomSzSlice := make([]room, 3)
}
func main() {
}
Run Code Online (Sandbox Code Playgroud)
当我尝试构建和运行它时,我收到以下错误:
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 }
Run Code Online (Sandbox Code Playgroud)
我做错了什么?
谢谢!
首先,您不能在结构内部分配/初始化。:= 运算符声明并赋值。但是,您可以简单地获得相同的结果。
这是一个简单、琐碎的示例,大致可以完成您正在尝试的操作:
type house struct {
s []string
}
func main() {
h := house{}
a := make([]string, 3)
h.s = a
}
Run Code Online (Sandbox Code Playgroud)
我从来没有这样写过,但如果它符合你的目的......它无论如何都会编译。
你可以声明在结构声明片,但你不能初始化。你必须通过不同的方式来做到这一点。
// 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),
}
}
Run Code Online (Sandbox Code Playgroud)
请参阅以上作为 runnable example on Go Playground
编辑
要根据评论中的要求部分初始化结构,可以简单地更改
func NewHouse(name string) *House{
return &House{
name: name,
}
}
Run Code Online (Sandbox Code Playgroud)
请runnable example on Go Playground再次将上述内容视为
归档时间: |
|
查看次数: |
8609 次 |
最近记录: |