Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading