golang read private attribute of a struct in another package

huangapple go评论125阅读模式
英文:

golang read private attribute of a struct in another package

问题

我理解,在Go语言中,我们有公有字段和私有字段。

  1. package main
  2. type User struct {
  3. DisplayName string
  4. title *string
  5. }

DisplayName 是公有的,所以我可以从另一个包中读取它。title 是私有的,我不能直接读取它。

如果我添加一个公有方法,像这样:

  1. package main
  2. type User struct {
  3. DisplayName string
  4. title *string
  5. }
  6. func (user *User) PublicTitle() string {
  7. return user.title
  8. }
  9. type EmployeeUser User

那么我应该能够通过 localUser.PublicTitle() 在另一个包中读取 title 吗?

  1. package utility
  2. var localUser *main.EmployeeUser
  3. localUser.PublicTitle()

我尝试过,似乎不起作用。我有点困惑。

谢谢帮助。

英文:

I understand on golang we have public and private fields

  1. package main
  2. type User struct {
  3. DisplayName string
  4. title *string
  5. }

Displayname is public so I can read it from another package. title is private I cannot read direclty

what about I add a public method like this

  1. package main
  2. type User struct {
  3. DisplayName string
  4. title *string
  5. }
  6. func (user *User) PublicTitle() string {
  7. return user.title
  8. }
  9. type EmployeeUser User

So I should be able to read title by localUser.PublicTitle() in another package?

  1. package utility
  2. var localUser *main.EmployeeUser
  3. localUser.PublicTitle()

I have tried it seems not working. I am a bit confused.

Thanks for help

答案1

得分: 2

类型EmployeeUser是一个新类型。当你基于现有类型定义一个新类型时,基类型的方法不会被提升到新类型中。

要实现这一点,你需要嵌入:

  1. type EmployeeUser struct {
  2. User
  3. }
英文:

The type EmployeeUser is a new type. When you define a new type based on an existing one, the methods of base type are not promoted to the new type.

To do that, you have to embed:

  1. type EmployeeUser struct {
  2. User
  3. }

huangapple
  • 本文由 发表于 2022年10月6日 09:07:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/73967726.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定