英文:
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
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论