我正在努力解决以下简化版问题。
我想初始化一个结构,其中包含一个切片的另一种类型的结构。
我看过各种示例,它们似乎是针对简单版本的,其中结构仅包含[] int等的一部分。
我似乎无法弄清楚初始化结构体/切片所需的内容。
Swells
切片可以是任意长度,包括空。
package main
import (
"fmt"
)
type Swell struct {
Slot uint
Height float32
Period float32
Dir uint
}
type ForecastHour struct {
Year uint
Month uint
Day uint
Hour uint
Swells []Swell
}
func NewForecastHour() *ForecastHour {
p := ForecastHour{}
p.Year = 2019
p.Month = 10
p.Day = 3
p.Hour = 13
p.Swells[0] := { Slot: 0, Height: 2.20, Period: 15.5,Dir: 300 }
p.Swells[1] := { Slot: 1, Height: 1.20, Period: 5.5,Dir: 90 }
p.Swells[2] := { Slot: 5, Height: 0.98, Period: 7.5,Dir: 180 }
return &p
}
func main() {
ThisHour := NewForecastHour()
fmt.Println(ThisHour)
}
运行上面的命令时,我得到:
./test.go:30:16: non-name p.Swells[0] on left side of :=
./test.go:30:23: syntax error: unexpected {, expecting expression
./test.go:31:8: syntax error: non-declaration statement outside function body
答案 0 :(得分:2)
首先,请注意,不能使用auto
将值分配给struct属性。要解决您的主要问题,您只需初始化:=
p.Swells
如果要添加任意数量的膨胀,则可以使用效率较低的append方法:
func NewForecastHour() *ForecastHour {
p := ForecastHour{}
p.Year = 2019
p.Month = 10
p.Day = 3
p.Hour = 13
p.Swells = make([]Swell, 3) // initialize with size 3
p.Swells[0] = Swell{ Slot: 0, Height: 2.20, Period: 15.5,Dir: 300 }
p.Swells[1] = Swell{ Slot: 1, Height: 1.20, Period: 5.5,Dir: 90 }
p.Swells[2] = Swell{ Slot: 5, Height: 0.98, Period: 7.5,Dir: 180 }
return &p
}
这在for循环中起作用。