dongqixuan3112 2016-02-05 22:36
浏览 69
已采纳

传递结构

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?

  • 写回答

3条回答 默认 最新

  • dongqi3533 2016-02-05 22:53
    关注

    In your main package you should specify

    var conf configuration.Config = configuration.Load()
    

    configuration refers to your imported package and Config is the exported struct (uppercase name) from that package. But you can also omit this, as the type can be inferred

    var conf = configuration.Load()
    

    As a side note: please don't use relative imports

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?