猿问

如何在 Go 中传递嵌套结构

一个小的 2 文件应用程序,它读取配置文件并将其存储在struct. 如何将部分配置struct传递给fetchTemperature函数?


配置


package configuration


type Config struct {

    Temperatures []struct {

        Temperature

    }

}


type Temperature struct {

    AppId string

}


func Load() Config {

    var c Config

    // -- 8< -- snip -- 8< --

    return c

}

主要的


package main


import "configuration"


var c configuration.Config = configuration.Load()


func main() {

    for _, t := range c.Temperatures {

        fetchTemperature(t)

    }

}


func fetchTemperature(t configuration.Temperature) {

    // -- 8< -- snip -- 8< --

}

给我:


cannot use t (type struct { configuration.Temperature }) as type configuration.Temperature in argument to fetchTemperature


不是t,configuration.Temperature如果不是,我该如何struct绕过?


米脂
浏览 156回答 1
1回答

茅侃侃

type Config struct {&nbsp; &nbsp; Temperatures []struct {&nbsp; &nbsp; &nbsp; &nbsp; Temperature&nbsp; &nbsp; }}t是Config.Temperatures[i]。对于Temperaturefrom anonymous struct { Temperature },写入t.Temperature以从结构中选择字段。例如,package mainimport "configuration"var c configuration.Config = configuration.Load()func main() {&nbsp; &nbsp; for _, t := range c.Temperatures {&nbsp; &nbsp; &nbsp; &nbsp; fetchTemperature(t.Temperature)&nbsp; &nbsp; }}func fetchTemperature(t configuration.Temperature) {&nbsp; &nbsp; //&nbsp; -- 8< -- snip -- 8< --}我怀疑你的困惑是因为你写的type Config struct {&nbsp; &nbsp; Temperatures []struct {&nbsp; &nbsp; &nbsp; &nbsp; Temperature&nbsp; &nbsp; }}Temperatures是一个匿名类型的切片struct { configuration.Temperature }。你可能想要的是type Config struct {&nbsp; &nbsp; Temperatures []Temperature}Temperatures是一个类型的切片configuration.Temperature。
随时随地看视频慕课网APP

相关分类

Go
我要回答