Go Stucts Quick Reference
How to declare and use golang struct.
Declaring a struct
type Customer struct {
ID int64
Name string
}
Using a struct
c := Customer{1, "iPax Ltd"}
fmt.Println(c.Name) // Prints: iPax Ltd
fmt.Println(c) // Prints: {1 iPax Ltd}
var cust Customer // Declaring cust as type of Customer
fmt.Println("This is an empty struct: ", cust)
cust.ID = 2
cust.Name = "iPax"
fmt.Printf("Customer name is %v and id is %v\n", cust.Name, cust.ID)
External documentation: fmt package documentation
Declare and fill a struct
var userID int64 = 2
name := "Diggz Ltd"
customer := Customer{
ID: userID,
Name: name,
}
fmt.Println(customer)
Struct with struct tag
type Task struct {
Name string `json:"name"`
Done bool `json:"done"`
}
Struct with several struct tags
type Task struct {
Name string `db:"name" json:"name"`
Done bool `db:"done" json:"done"`
}
External documentation: Go lang struct tags
Declare a slice of structs
type TaskList []Task
Adding an element to a slice of structs
var taskList TaskList
task := Task{"Hello", false}
taskList = append(taskList, task)
fmt.Println(taskList)
Declare a map of structs
type TaskList map[string]Task
Adding an element to a map of structs
var taskList = make(TaskList)
task := Task{"Hello", false}
taskList["first"] = task
fmt.Println(taskList)