繁体   English   中英

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

在Go Playground上看到以上内容作为可运行的示例


编辑

要按照注释中的要求部分初始化该结构,可以简单地进行更改

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

请再次将以上内容作为Go Playground上可运行示例

首先,您不能在结构内部分配/初始化。 :=运算符进行声明和分配。 但是,您可以简单地实现相同的结果。

这是一个简单的琐碎示例,可以大致完成您要尝试的操作:

type house struct {
    s []string
}

func main() {
    h := house{}
    a := make([]string, 3)
    h.s = a
}

我从来没有那样写过,但是如果它满足您的目的……无论如何都会编译。

你也可以参考这个: https://golangbyexample.com/struct-slice-field-go/

type student struct {
    name   string 
    rollNo int    
    city   string 
}

type class struct {
    className string
    students  []student
}

goerge := student{"Goerge", 35, "Newyork"}
john := student{"Goerge", 25, "London"}

students := []student{goerge, john}

class := class{"firstA", []student{goerge, john}}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM