如何从Golang中的结构访问特定字段

Suppose I have the following code:

type User struct {
    ID              string
    Username        string
    Name            string
    Password        string
}

What I want to do is create another struct that can access certain fields from the User struct, instead of accessing all of it, to prevent people from seeing the password, for example. This does not work:

type Note struct {
    ID         string
    Text       string
    UserID     User.ID          
}

Is there any way to do this, or do I simply create the Note.UserID field to have the same data type as the ID in the User struct?

Assuming the types are in different packages you can do this by exporting vs not exporting the fields. A field who's name begins with a lower case letter is not exported, meaning it is not visible outside the package where it is declared/defined. So, in this case if the user existed in one package, call it user while the other type were declared in another you could accomplish this 'hiding' of properties by changing the definition to;

type User struct {
    ID              string
    username        string
    name            string
    password        string
}

If the two types live in the same package there is no way of making a field private/hidden/ect, everything will be available in that scope.

The Go Programming Language Specification

Exported identifiers

An identifier may be exported to permit access to it from another package. An identifier is exported if both:

the first character of the identifier's name is a Unicode upper case letter (Unicode class "Lu"); and

the identifier is declared in the package block or it is a field name or method name.

All other identifiers are not exported.

Give User its own package and don't export the password.

For example,

package user

type User struct {
    ID       string
    Username string
    Name     string
    password string
}

func (u *User) IsPassword(password string) bool {
    return password == u.password
}