-1

I try create package config in my example project but something doesn't work as I expected, I have folder structure:

config/config.go // package config
main.go  // package main

and I want use config in my main file:

func main() {
    conf := config.GetConf()

    db := dbConn{
        schemas:  map[string]*sql.DB{},
        url:      fmt.Sprintf("tcp(%s)", conf.db['dev']),
        username: db.user,
        password: db.password,
    }
    db.create()
}

my config file:

type Config struct {
    db         map[string]string
    user     string
    password string
}

func GetConf() *Config {
    config := Config{
        db: map[string]string{
            "dev": "database.url",
        },
        user: "root",
        password: "pass",
    }

    return &config
}

compiler return error: conf.db undefined (cannot refer to unexported field or method db)

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
Sebastian
  • 166
  • 2
  • 16
  • This is covered on page 3 of the "basics" section of the Tour of Go: https://tour.golang.org/basics/3 – Adrian Aug 14 '18 at 13:19
  • Possible duplicate of [Invoke golang struct function gives "cannot refer to unexported field or method"](https://stackoverflow.com/questions/24487943/invoke-golang-struct-function-gives-cannot-refer-to-unexported-field-or-method) – Jonathan Hall Aug 14 '18 at 15:32

1 Answers1

3

It is a compile-time error to refer to unexported identifiers from other packages (other than the declaring package).

Export the identifiers (start them with an uppercase letter), and it will work.

type Config struct {
    DB       map[string]string
    User     string
    Password string
}

func GetConf() *Config {
    config := Config{
        DB: map[string]string{
            "dev": "database.url",
        },
        User:     "root",
        Password: "pass",
    }

    return &config
}

And in your main:

func main() {
    conf := config.GetConf()

    db := dbConn{
        schemas:  map[string]*sql.DB{},
        url:      fmt.Sprintf("tcp(%s)", conf.DB['dev']),
        username: conf.User,
        password: conf.Password,
    }
    db.create()
}
icza
  • 389,944
  • 63
  • 907
  • 827