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

发布时间: 2019-10-26 14:20:12 作者: 大象笔记

今天将 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 访问权限控制

我是一名山东烟台的开发者,联系作者