传递结构

I am new to go and coming from a Ruby background. I am trying to understand code structuring in a world without classes and am probably making the mistake wanting to do it "the Ruby way" in Go.

I am trying to refactor my code to make it more modular / readable so I moved the loading of the configuration file to its own package. Good idea?

package configuration

import "github.com/BurntSushi/toml"

type Config struct {
    Temperatures []struct {
        Degrees int
        Units string
    }
}

func Load() Config {
    var cnf Config
    _, err := toml.DecodeFile("config", &cnf)
    if err != nil {
        panic(err)
    }
    return cnf
}

Now, in my main package:

package main

import "./configuration"

var conf Configuration = configuration.Load()

Gives undefined: Config. I understand why. I could copy the struct definition in the main package but that's not very DRY.

It's my understanding passing around structs like this is a bad practice as it makes your code harder to understand (now everyone needs to know about my Config struct).

Is hiding logic in a package like I am trying to do here a good idea in Go? If so, what's the "Go" way to pass this Config struct around?

查看全部
dongqixuan3112
dongqixuan3112
2016/02/05 22:36
  • struct
  • 点赞
  • 收藏
  • 回答
    私信
满意答案
查看全部

3个回复