绕过结构

时间:2016-02-05 22:36:44

标签: go struct

我是新手,来自Ruby背景。我试图理解没有类的世界中的代码结构,并且我可能错误地想要在Go中以“Ruby方式”来做它。

我正在尝试重构我的代码以使其更具模块化/可读性,因此我将配置文件的加载移动到了自己的包中。好主意?

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
}

现在,在我的主要包裹中:

package main

import "./configuration"

var conf Configuration = configuration.Load()

给予undefined: Config。我理解为什么。我可以在主包中复制结构定义,但这不是很干。

这是我理解传递这样的结构是一种不好的做法,因为它使你的代码更难理解(现在每个人都需要知道我的Config结构)。

隐藏逻辑在一个包中,就像我想在Go中做一个好主意吗?如果是这样,那么传递这个Config结构的“Go”方式是什么?

3 个答案:

答案 0 :(得分:4)

在主套餐中,您应指定

var conf configuration.Config = configuration.Load()

configuration引用您导入的包,Config是该包中的导出结构(大写名称)。但你也可以省略这一点,因为可以推断出类型

var conf = configuration.Load()

作为旁注:请不要使用相对进口

答案 1 :(得分:1)

在Go导入中,你总是声明你的包的完整路径,不要在导入中使用相对路径,最好的例子是存在于的toml import import "github.com/BurntSushi/toml": GOPATH / src目录/ github.com / BurntSushi / toml GOPATH / pkg / _ / github.com/BurntSushi/toml

然后构建您的包和main.go

package main

import "mypackage/configuration"

func main() {
   // configuration contain all funcs & structs 
   var conf configuration.Config = configuration.Load()
}

去吧,这不是红宝石。

Ref Packages:https://golang.org/doc/code.html

答案 2 :(得分:1)

为什么不直接导入配置包然后执行Go的变量声明/ instatiation快捷方式?也许我错过了什么。

package main

import "mypackage/configuration"

func main() {
   conf := configuration.Load()
}
相关问题