-
Notifications
You must be signed in to change notification settings - Fork 0
20210211golang的大小写(公私有问题)
zqy edited this page Feb 11, 2021
·
1 revision
如main.go中存在如下内容:
type User struct {
name string
age int
}
func main() {
user:=User{"Tom",18}
if userJSON,err:=json.Marshal(user);err==nil{
fmt.Println(string(userJSON)) //数据无法解析
}
}
main.go或许属于main包,但是这里用到了package encoding/json
对于json包来说main包是外包,因此name和age都无法解析
而对于“解析”,其实不仅仅解析,“跨”包的任何操作都无法完成,如跨包调用内部字段:
package user
type User struct {
name string
age int
}
/*----*/
package main
import user
u := user.User{}
u.name ="tom"//会失败
“跨”包的初始化也是不允许的:
package user
type User struct {
name string
age int
}
/*----*/
package main
import user
u := user.User{name: "tom",age:13}//会失败
需要为其设计公有初始化方法才行:
package user
type User struct {
name string
age int
}
func (p User)Init({
p.name ="Tom"
p.age =13
}
/*----*/
package main
import user
u := user.User{}
u.Init//成功