Basic declaration
suggest changeA basic struct is declared as follows:
// User describes a user
type User struct {
FirstName, LastName string
Email string
Age int
userID int
}
// FullName returns full name of a user
func (u *User) FullName() string {
return fmt.Sprintf("%s %s", u.FirstName, u.LastName)
}
func main() {
// zero value of struct
var u User
fmt.Printf("u: %#v\n\n", u)
// pu is *User i.e. a pointer to User struct
pu := new(User)
pu.Age = 33
fmt.Printf("*pu: %#v\n", *pu)
// &User{} is the same as new(User)
pu = &User{}
pu.Age = 18
fmt.Printf("*pu: %#v\n", *pu)
pu.FirstName, pu.LastName = "Jane", "Doe"
fmt.Printf("pu.FullName(): %s\n", pu.FullName())
}
u: main.User{FirstName:"", LastName:"", Email:"", Age:0, userID:0}
*pu: main.User{FirstName:"", LastName:"", Email:"", Age:33, userID:0}
*pu: main.User{FirstName:"", LastName:"", Email:"", Age:18, userID:0}
pu.FullName(): Jane Doe
Each value is called a field.
Fields are usually written one per line, with the field’s name preceeding its type.
Consecutive fields of the same type may be combined, as FirstName
and LastName
in the above example.
Field names that start with upper case (FirstName
, Email
) are public i.e. accesible by all code.
Field names that start with lower case (userID
) are private and only accessible by code in the same package.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents