簡體   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