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条)

报告相同问题?

悬赏问题

  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能
  • ¥15 jmeter脚本回放有的是对的有的是错的
  • ¥15 r语言蛋白组学相关问题
  • ¥15 Python时间序列如何拟合疏系数模型
  • ¥15 求学软件的前人们指明方向🥺
  • ¥50 如何增强飞上天的树莓派的热点信号强度,以使得笔记本可以在地面实现远程桌面连接
  • ¥20 双层网络上信息-疾病传播