登录
首页 >  Golang >  Go问答

结构的引用的回归

来源:stackoverflow

时间:2024-02-20 15:54:21 287浏览 收藏

小伙伴们有没有觉得学习Golang很有意思?有意思就对了!今天就给大家带来《结构的引用的回归》,以下内容将会涉及到,若是在学习中对其中部分知识点有疑问,或许看了本文就能帮到你!

问题内容

我知道很多人已经问过这个问题,我研究并尝试过,但我不明白,首先这是我的功能:

func Config() *config {
    configfile := viper.New()
    configfile.SetConfigFile("config.toml")
    configfile.ReadInConfig()
    type configstruct struct {
        first_launch             bool
        generate_desktop_file    bool
        systemwide_desktop_entry bool
        webapps_directory        string
        locale                   string
    }
    config := configstruct{
        first_launch:             configfile.GetBool("general.first_launch"),
        generate_desktop_file:    configfile.GetBool("general.generate_desktop_file"),
        systemwide_desktop_entry: configfile.GetBool("general.systemwide_desktop_entry"),
        webapps_directory:        configfile.GetString("general.webapps_directory"),
        locale:                   configfile.GetString("general.locale")}
    fmt.Println(reflect.TypeOf(config))
    return &config
}

我尝试让它以这种方式工作,就像很多人写的那样,但后来我通过 func config() *config 行得到了这个错误。这是错误:undefined:config。显然我做错了什么,但我不知道我做错了什么。旁注,我对 go 完全陌生,之前我只使用过 python

我尝试将 *config 添加到 func 中,并在 func 内部添加了一个 return &config,我期望它将返回一个我可以使用的指针,但我收到错误:undefinied config


正确答案


您应该从函数中返回 *configstruct。在函数外部定义结构总是一个好主意,否则它会绑定在 function 范围内,请参阅下面更新的代码。

type configstruct struct {
    first_launch             bool
    generate_desktop_file    bool
    systemwide_desktop_entry bool
    webapps_directory        string
    locale                   string
}
    
func Config() *configstruct {
    configfile := viper.New()
    configfile.SetConfigFile("config.toml")
    configfile.ReadInConfig()
        
    config := configstruct{
        first_launch:             configfile.GetBool("general.first_launch"),
        generate_desktop_file:    configfile.GetBool("general.generate_desktop_file"),
        systemwide_desktop_entry: configfile.GetBool("general.systemwide_desktop_entry"),
        webapps_directory:        configfile.GetString("general.webapps_directory"),
        locale:                   configfile.GetString("general.locale"),
    }

    fmt.Println(reflect.TypeOf(config))
    return &config
}

以上就是本文的全部内容了,是否有顺利帮助你解决问题?若是能给你带来学习上的帮助,请大家多多支持golang学习网!更多关于Golang的相关知识,也可关注golang学习网公众号。

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>