Struct in Golang
In this tutorial, we'll learn about Struct (Structure) in Golang.
What is Structure (Struct) in Golang?
-
A struct is a composite data type in Golang.
-
It allows us to group together values of different types into a single entity.
-
It is similar to a class in object-oriented programming languages.
-
Structs are useful for representing real-world entities, such as a person, a car, or any other complex data structure.
How to define a Struct in Golang?
To define a struct in Go, you use the type keyword followed by the struct's name and a list of its fields enclosed in curly braces {}. Each field has a name and a type.
type Student struct {
Name string
Age int
}
Creating Struct Instances
Once we've defined a struct, we can create instances of that struct using the following syntax:
student := Student{
Name: "Rahul Singh",
Age: 19,
}
Here, we define a Student struct with two fields: Name and Age.
Accessing Struct Fields
To access the fields of a struct, we can use the dot . operator followed by the field name.
Example:
package main
import "fmt"
type Student struct {
Name string
Age int
}
func main() {
student1 := Student{
Name: "Rahul Singh",
Age: 19,
}
student2 := Student{
Name: "KL Rahul",
Age: 28,
}
fmt.Println(student1.Name)
fmt.Println(student1.Age)
fmt.Println(student2.Name)
fmt.Println(student2.Age)
}
Output:
Rahul Singh
19
KL Rahul
28
How to Update Struct Fields in Golang?
We can update the values of struct fields by assigning new values to them using the dot . operator.
Example:
package main
import "fmt"
type Student struct {
Name string
Age int
}
func main() {
student1 := Student{
Name: "Rahul Singh",
Age: 19,
}
student2 := Student{
Name: "KL Rahul",
Age: 28,
}
student1.Name = "Steve Smith"
student1.Age = 12
fmt.Println(student1.Name)
fmt.Println(student1.Age)
fmt.Println(student2.Name)
fmt.Println(student2.Age)
}
Output:
Steve Smith
12
KL Rahul
28