Tutorial by Examples

A basic struct is declared as follows: type User struct { FirstName, LastName string Email string Age int } 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 sa...
Struct fields whose names begin with an uppercase letter are exported. All other names are unexported. type Account struct { UserID int // exported accessToken string // unexported } Unexported fields can only be accessed by code within the same package. As such, if you are ev...
Composition provides an alternative to inheritance. A struct may include another type by name in its declaration: type Request struct { Resource string } type AuthenticatedRequest struct { Request Username, Password string } In the example above, AuthenticatedRequest will con...
Struct methods are very similar to functions: type User struct { name string } func (u User) Name() string { return u.name } func (u *User) SetName(newName string) { u.name = newName } The only difference is the addition of the method receiver. It may be declared either a...
It is possible to create an anonymous struct: data := struct { Number int Text string } { 42, "Hello world!", } Full example: package main import ( "fmt" ) func main() { data := struct {Number int; Text string}{42, "Hello worl...
Struct fields can have tags associated with them. These tags can be read by the reflect package to get custom information specified about a field by the developer. struct Account { Username string `json:"username"` DisplayName string `json:"display_name"` F...
A struct can simply be copied using assignment. type T struct { I int S string } // initialize a struct t := T{1, "one"} // make struct copy u := t // u has its field values equal to t if u == t { // true fmt.Println("u and t are equal") // Prints: &qu...
A value of a struct type can be written using a struct literal that specifies values for its fields. type Point struct { X, Y int } p := Point{1, 2} The above example specifies every field in the right order. Which is not useful, because programmers have to remember the exact fields in order. M...
A struct is a sequence of named elements, called fields, each of which has a name and a type. Empty struct has no fields, like this anonymous empty struct: var s struct{} Or like this named empty struct type: type T struct{} The interesting thing about the empty struct is that, its size is z...

Page 1 of 1