A struct, short for “structure,” is a way to bundle together multiple pieces of data with different types into a single entity. Unlike arrays, which store multiple values of the same type, structs allow different types to coexist within a single unit, making them useful for organizing related data.
Declaring a Struct
In Go, a struct is defined using the type
keyword followed by the struct name and its members.
Syntax:
type structName struct { member1 datatype member2 datatype member3 datatype }
Example:
Here, Motorcycle
is a struct that groups multiple details about a motorcycle, such as brand, model, year, and price.
type Motorcycle struct { brand string model string year int price int }
Each member of the struct can have a different data type. In this example, brand
and model
are strings, while year
and price
are integers.
Accessing Struct Members
To access the elements within a struct, use the dot (.
) operator.
Example:
Below, two instances of the Motorcycle
struct (bike1
and bike2
) are created and their attributes are assigned values.
package main import ("fmt") type Motorcycle struct { brand string model string year int price int } func main() { var bike1 Motorcycle var bike2 Motorcycle // Assigning values to bike1 bike1.brand = "Yamaha" bike1.model = "R1" bike1.year = 2022 bike1.price = 15000 // Assigning values to bike2 bike2.brand = "Ducati" bike2.model = "Panigale V4" bike2.year = 2023 bike2.price = 25000 // Printing bike1 details fmt.Println("Brand: ", bike1.brand) fmt.Println("Model: ", bike1.model) fmt.Println("Year: ", bike1.year) fmt.Println("Price: $", bike1.price) // Printing bike2 details fmt.Println("Brand: ", bike2.brand) fmt.Println("Model: ", bike2.model) fmt.Println("Year: ", bike2.year) fmt.Println("Price: $", bike2.price) }
Output:
Brand: Yamaha Model: R1 Year: 2022 Price: $15000 Brand: Ducati Model: Panigale V4 Year: 2023 Price: $25000
Passing a Struct as a Function Argument
Structs can also be passed as arguments to functions, allowing for cleaner code when working with structured data.
Example:
The following program defines a function printMotorcycle()
that takes a Motorcycle
struct as an argument and prints its details.
package main import ("fmt") type Motorcycle struct { brand string model string year int price int } func main() { var bike1 Motorcycle var bike2 Motorcycle // Assigning values to bike1 bike1.brand = "Kawasaki" bike1.model = "Ninja ZX-10R" bike1.year = 2021 bike1.price = 18000 // Assigning values to bike2 bike2.brand = "Honda" bike2.model = "CBR1000RR" bike2.year = 2022 bike2.price = 20000 // Calling function to print details printMotorcycle(bike1) printMotorcycle(bike2) } func printMotorcycle(bike Motorcycle) { fmt.Println("Brand: ", bike.brand) fmt.Println("Model: ", bike.model) fmt.Println("Year: ", bike.year) fmt.Println("Price: $", bike.price) }
Output:
Brand: Kawasaki Model: Ninja ZX-10R Year: 2021 Price: $18000 Brand: Honda Model: CBR1000RR Year: 2022 Price: $20000