简体   繁体   中英

golang read private attribute of a struct in another package

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

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM