golang read private attribute of a struct in another package

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

golang read private attribute of a struct in another package

问题

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

package main

type User struct {
	DisplayName string
	title       *string
}

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

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

package main

type User struct {
	DisplayName string
	title       *string
}

func (user *User) PublicTitle() string {
	return user.title
}

type EmployeeUser User

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

package utility

var localUser *main.EmployeeUser

localUser.PublicTitle()

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

谢谢帮助。

英文:

I understand on golang we have public and private fields

package main
type User struct {

	DisplayName string 

	title *string 
}

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

package main
type User struct {

	DisplayName string 

	title *string 
}
func (user *User) PublicTitle() string {
  return user.title
}

type EmployeeUser User

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

package utility

var localUser *main.EmployeeUser
 
localUser.PublicTitle()

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

Thanks for help

答案1

得分: 2

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

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

type EmployeeUser struct {
    User
}
英文:

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:

type EmployeeUser struct {
    User
}

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:

确定