Go Structures
A struct (short for structure) combines several members, which can have different data types, into one variable.
An array also holds many values in one variable, but they must all share one data type. A struct has no such restriction.
That makes structs handy for keeping related data together as records.
Declare a Struct
Declaring a struct in Go takes two keywords: type and struct.
Tip: The members of Person don't all share a type. name and job are strings, while age and salary are integers.
Struct Syntax
type struct_name struct {
member1 datatype;
member2 datatype;
member3 datatype;
...
}
Struct Declaration
type Person struct {
name string
age int
job string
salary int
}
Access Struct Members
To reach a member of a struct, write the struct variable's name, then the dot operator (.), then the member's name. Here it is used both to set and to read the members of two variables.
Example
Output: Go program and captured output
package main
import ("fmt")
type Person struct {
name string
age int
job string
salary int
}
func main() {
var pers1 Person
var pers2 Person
pers1.name = "Hege"
pers1.age = 45
pers1.job = "Teacher"
pers1.salary = 6000
pers2.name = "Cecilie"
pers2.age = 24
pers2.job = "Marketing"
pers2.salary = 4500
fmt.Println("Name: ", pers1.name)
fmt.Println("Age: ", pers1.age)
fmt.Println("Job: ", pers1.job)
fmt.Println("Salary: ", pers1.salary)
fmt.Println("Name: ", pers2.name)
fmt.Println("Age: ", pers2.age)
fmt.Println("Job: ", pers2.job)
fmt.Println("Salary: ", pers2.salary)
}
Pass Struct as Function Arguments
A struct can also be passed to a function as an argument. Here printPerson() receives a Person and prints its members, so the printing code doesn't have to be repeated.
Example
Output: Go program and captured output
package main
import ("fmt")
type Person struct {
name string
age int
job string
salary int
}
func printPerson(pers Person) {
fmt.Println("Name: ", pers.name)
fmt.Println("Age: ", pers.age)
fmt.Println("Job: ", pers.job)
fmt.Println("Salary: ", pers.salary)
}
func main() {
var pers1 Person
var pers2 Person
pers1.name = "Hege"
pers1.age = 45
pers1.job = "Teacher"
pers1.salary = 6000
pers2.name = "Cecilie"
pers2.age = 24
pers2.job = "Marketing"
pers2.salary = 4500
printPerson(pers1)
printPerson(pers2)
}