Golang 访问 struct 成员变量时报错 cannot refer to unexported field or method id

文章目录

    今天将 Golang Gin 项目拆分成了 models, controllers 两个 package,但是当在 controller 中打印一个 models package 中的 struct 结构体的成员变量时,报错:

    kv.id undefined (cannot refer to unexported field or method id)

    具体的代码为:

    // models package
    type KV struct {
    	id         int
    	key        string
    	value      string
    	updated_at string
    }
    
    // controllers package
    kv, _ := models.GetValue("2")   // GetValue 返回 &kv, error
    log.Println(kv.id)
    

    Google 了一下才知道,结构体中的成员变量,只有首字母大写,才能在其定义的 package 以外访问。而在同一个 package 内,就不会有此限制。

    所以,需要修改 KV struct 的代码为:

    type KV struct {
    	Id         int
    	Key        string
    	Value      string
    	Updated_at string
    }
    
    log.Println(kv.Id)
    

    struct 访问权限控制

    • 字段变量名首字母大写的,称之为 exported field。package 外可以访问。
    • 字段变量名首字母小写的,称之为 unexported field。package 外不可访问。

    关于作者 🌱

    我是来自山东烟台的一名开发者,有感兴趣的话题,或者软件开发需求,欢迎加微信 zhongwei 聊聊,或者关注我的个人公众号“大象工具”, 查看更多联系方式