登录
首页 >  Golang >  Go问答

如何填充未知尺寸的结构片段

来源:stackoverflow

时间:2024-02-25 19:54:26 437浏览 收藏

本篇文章给大家分享《如何填充未知尺寸的结构片段》,覆盖了Golang的常见基础知识,其实一个语言的全部知识点一篇文章是不可能说完的,但希望通过这些问题,让读者对自己的掌握程度有一定的认识(B 数),从而弥补自己的不足,更好的掌握它。

问题内容

我正在尝试解决以下问题的简化版本。

我想初始化一个结构体,其中包含另一种类型结构体的切片。

我查看了各种示例,它们似乎是针对更简单的版本,其中结构仅包含 []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

解决方案


首先,请注意,您无法使用 := 为结构体属性赋值。要解决您的主要问题,您只需初始化 p.swells

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
}

Demo

如果要添加任意数量的 swell,则可以使用效率较低的追加方法:

p.Swells = []Swell{}
p.Swells = append(p.Swells, Swell{ Slot: 0, Height: 2.20, Period: 15.5,Dir: 300 })
p.Swells = append(p.Swells, Swell{ Slot: 1, Height: 1.20, Period: 5.5,Dir: 90 })
p.Swells = append(p.Swells, Swell{ Slot: 5, Height: 0.98, Period: 7.5,Dir: 180 })

这适用于 for 循环。

今天带大家了解了的相关知识,希望对你有所帮助;关于Golang的技术知识我们会一点点深入介绍,欢迎大家关注golang学习网公众号,一起学习编程~

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>