标识符通过大小写来区分是否公开,
没有公开 的标识符只能在本包使用,别的包无法使用,
工厂模式解决问题
代码
src\go_code\pubsymbol\main\main.go
package mainimport ("fmt"// 引包"go_code/pubsymbol/counters""go_code/pubsymbol/model")func main() {// 创建一个未公开类型的变量,并初始化为10counter := counters.New(10)fmt.Printf("counter类型:%T, 值:%v \n ", counter, counter) // counter类型:counters.AlertCounter, 值:10// 创建 Student 结构体变量/* stu := model.Student{Name: "tom",Age: 2,} */stu := model.NewStudent("tom02", 3)fmt.Println("stu = ", *stu) // {tom02 3}fmt.Println("stu.Name = ", stu.Name) // tom02fmt.Println("stu.score = ", stu.GetScore()) // 没有赋值, 默认零值 0fmt.Println("stu = ", *stu) // {tom02 3}}
src\go_code\pubsymbol\counters\counters.go
package counters// alertCounter 是一个未公开的类型,用于保存告警次数type alertCounter int// 工厂函数// New 创建并返回一个未公开的 alertCounter 类型的值func New(value int) alertCounter {return alertCounter(value)}
src\go_code\pubsymbol\model\model.go
package model// 公开 Student 结构体变量type student struct {Name stringAge intscore float64 // 未公开的字段,怎么在别包获取?}func NewStudent(name string, age int) *student {return &student{Name: name,Age: age,}}// 创建一个对外公开的方法,返回其私有的字段 scorefunc (stu *student) GetScore() float64 {return stu.score}
代码解读
- 将工厂函数命名为New是Go语言的一个习惯,这个New函数做了一些有意思的事情:创建了一个未公开的类型的值,并将这个值返回给调用者。
- 标识符才有公开或者未公开的属性,值没有。
