gpt4 book ai didi

go - 在函数中返回结构的值并在另一个包中使用它

转载 作者:数据小太阳 更新时间:2023-10-29 03:31:34 26 4
gpt4 key购买 nike

我尝试在我的示例项目中创建包配置,但有些东西没有像我预期的那样工作,我有文件夹结构:

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

我想在我的主文件中使用配置:

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()
}

我的配置文件:

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
}

编译器返回错误:conf.db undefined (cannot refer to unexported field or method db)

最佳答案

从其他包(声明包除外)引用未导出的标识符是一个编译时错误。

导出标识符(以大写字母开头),它将起作用。

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
}

在你的主要部分:

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()
}

关于go - 在函数中返回结构的值并在另一个包中使用它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51839132/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com