Go Structs #
A struct (short for structure) in Go is used to group together members of different data types into a single variable. While arrays store multiple values of the same type, structs store multiple values of different types. Structs are useful for creating records.
Declare a Struct #
Use the type
and struct
keywords to declare a struct:
type Person struct {
name string
age int
job string
salary int
}
Tip: Struct members can have different data types. For example, name
and job
are string
, while age
and salary
are int
.
Access Struct Members #
Use the dot operator (.
) to access members of a struct.
package main
import "fmt"
type Person struct {
name string
age int
job string
salary int
}
func main() {
var pers1 Person
var pers2 Person
// Pers1 specification
pers1.name = "Hege"
pers1.age = 45
pers1.job = "Teacher"
pers1.salary = 6000
// Pers2 specification
pers2.name = "Cecilie"
pers2.age = 24
pers2.job = "Marketing"
pers2.salary = 4500
// Access and print Pers1 info
fmt.Println("Name: ", pers1.name)
fmt.Println("Age: ", pers1.age)
fmt.Println("Job: ", pers1.job)
fmt.Println("Salary: ", pers1.salary)
// Access and print Pers2 info
fmt.Println("Name: ", pers2.name)
fmt.Println("Age: ", pers2.age)
fmt.Println("Job: ", pers2.job)
fmt.Println("Salary: ", pers2.salary)
}
Result:
Name: Hege
Age: 45
Job: Teacher
Salary: 6000
Name: Cecilie
Age: 24
Job: Marketing
Salary: 4500
Pass Struct as Function Arguments #
Structs can also be passed to functions as arguments:
package main
import "fmt"
type Person struct {
name string
age int
job string
salary int
}
func main() {
var pers1 Person
var pers2 Person
// Pers1 specification
pers1.name = "Hege"
pers1.age = 45
pers1.job = "Teacher"
pers1.salary = 6000
// Pers2 specification
pers2.name = "Cecilie"
pers2.age = 24
pers2.job = "Marketing"
pers2.salary = 4500
// Print info by calling a function
printPerson(pers1)
printPerson(pers2)
}
func printPerson(pers Person) {
fmt.Println("Name: ", pers.name)
fmt.Println("Age: ", pers.age)
fmt.Println("Job: ", pers.job)
fmt.Println("Salary: ", pers.salary)
}
Result:
Name: Hege
Age: 45
Job: Teacher
Salary: 6000
Name: Cecilie
Age: 24
Job: Marketing
Salary: 4500
Tip: Passing structs to functions is useful to handle and organize structured data efficiently.