Cimm
Cimm

Reputation: 4775

Passing around structs

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?

Upvotes: 1

Views: 331

Answers (3)

user2529177
user2529177

Reputation: 71

why don't you just import the configuration package and then do Go's variable declaration/instatiation shortcut? Maybe I'm missing something.

package main

import "mypackage/configuration"

func main() {
   conf := configuration.Load()
}

Upvotes: 1

Kiramishima
Kiramishima

Reputation: 192

in Go imports you always declare the full path of you package, dont use relative paths in imports, best example is that toml import import "github.com/BurntSushi/toml" that exist in: GOPATH/src/github.com/BurntSushi/toml GOPATH/pkg/_/github.com/BurntSushi/toml

Then build you package and main.go

package main

import "mypackage/configuration"

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

Go it is not ruby.

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

Upvotes: 1

Danilo
Danilo

Reputation: 3327

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

Upvotes: 4

Related Questions