eclipse运行go test_Go语言面向对象编程-封装

Golang提供包级别(相对于类而言)的封装。Go没有public、private或protected关键字,控制可见性的唯一机制是使用标识符首字母大写格式

  • 首字母大写的标识符是可以导出的。标识符大写首字母表示这是可导出的标识符,即能从其它包中可以访问该标识符。
  • 首字母非大写的标识符是不可以导出的。标识符小写首字母表示标识符不可导出,即只能从同一个包中访问该标识符。

是否可以导出的标识符有以下五种:

  • 构体
  • 结构体方法
  • 结构体字段
  • 函数
  • 变量

下面的示例中演示以上五种标识符可否导出的情形,data.go是源文件,指定其为model包:

  • 结构体
  • 结构体Person是可导出的
  • 结构体company是不可导出的
  • 结构体方法
  • Person结构体的方法GetAge()是可导出的
  • Person结构体的方法getName()是不可导出的
  • 结构体字段
  • Person结构体的字段Name是可导出的
  • Person结构体的方法age是不可导出的
  • 函数
  • 函数GetPerson()是可导出的
  • 函数getCompanyName()是不可导出的
  • 变量
  • 变量CompanyName是可导出的
  • 变量companyLocation是不可导出的
8eedb44c1adae2f4926b476cf2a1f81e.png

test.go是测试model包的代码

d7e25b1120544df37308a9e3a5c5e89d.png

运行此文件时,它可以访问data.go中所有导出和未导出的字段,因为两者都位于model包中。没有编译错误,它给出以下输出:

&{test 21}

&{}

21

test

test

21

Model Package:

test

21

&{test 21}

test

somecity

test

把上面的文件test.go到另一个名为view的包。现在查看当运行“go build test.go”时的输出,它给出编译错误,所有编译错误都是由于无法引用未导出的字段

65e1ce1c8e528e7923d2e0b3c2566576.png

结果:

test.go:13:3: unknown field 'age' in struct literal of type model.Person

test.go:17:8: cannot refer to unexported name model.company

test.go:17:8: undefined: model.company

test.go:22:15: p.getName undefined (cannot refer to unexported field or method model.(*Person).getName)

test.go:26:15: p.age undefined (cannot refer to unexported field or method age)

test.go:31:17: cannot refer to unexported name model.getCompanyName

test.go:31:17: undefined: model.getCompanyName

test.go:35:14: cannot refer to unexported name model.companyLocation

test.go:35:14: undefined: model.companyLocation

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值