简体   繁体   中英

How to pass a nested struct in Go

A little 2 file application that reads a config file and stores it in a struct . How do pass part of the config struct to the fetchTemperature function?

Configuration

package configuration

type Config struct {
    Temperatures []struct {
        Temperature
    }
}

type Temperature struct {
    AppId string
}

func Load() Config {
    var c Config
    // -- 8< -- snip -- 8< --
    return c
}

Main

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

Gives me:

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

Isn't t of configuration.Temperature and if not, how do I pass the struct around?

type Config struct {
    Temperatures []struct {
        Temperature
    }
}

t is Config.Temperatures[i] . For Temperature from anonymous struct { Temperature } , write t.Temperature to select the field from the struct.

For example,

package main

import "configuration"

var c configuration.Config = configuration.Load()

func main() {
    for _, t := range c.Temperatures {
        fetchTemperature(t.Temperature)
    }
}

func fetchTemperature(t configuration.Temperature) {
    //  -- 8< -- snip -- 8< --
}

I suspect that your confusion arose because you wrote

type Config struct {
    Temperatures []struct {
        Temperature
    }
}

Temperatures is a slice of type anonymous struct { configuration.Temperature } .

What you probably wanted was

type Config struct {
    Temperatures []Temperature
}

Temperatures is a slice of type configuration.Temperature .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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