Struct in Go
In this tutorial, we will learn about structs in Go. Struct is short for Structures. We will cover the basics of defining and using structs, including how to create, access, and modify struct fields.
Understanding Structs in Go
A struct in Go is a composite data type that groups together variables under a single name. These variables, known as fields, can have different data types.
Defining a Struct
Structs in Go are defined using the struct
keyword, followed by the field names and their types.
type Person struct {
Name string
Age int
}
Creating an Instance of a Struct
You can create an instance of a struct by using the struct type followed by the field values in curly braces.
p := Person{Name: "Alice", Age: 25}
Accessing Struct Fields
Struct fields can be accessed using the dot operator.
fmt.Println(p.Name)
fmt.Println(p.Age)
Modifying Struct Fields
Struct fields can be modified by assigning new values to them.
p.Age = 26
Example 1: Defining and Creating a Struct
We can define and create an instance of a struct in Go.
For example,
- Define a struct named
Person
with fieldsName
andAge
. - Create an instance of the
Person
struct with initial values. - Print the struct to the console.
Go Program
package main
import "fmt"
type Person struct {
Name string
Age int
}
func main() {
p := Person{Name: "Alice", Age: 25}
fmt.Println(p)
}
Output
{Alice 25}
Example 2: Accessing Struct Fields
We can access fields of a struct in Go using the dot operator.
For example,
- Create an instance of the
Person
struct with initial values. - Access and print the fields
Name
andAge
to the console.
Go Program
package main
import "fmt"
type Person struct {
Name string
Age int
}
func main() {
p := Person{Name: "Alice", Age: 25}
fmt.Println(p.Name)
fmt.Println(p.Age)
}
Output
Alice 25
Example 3: Modifying Struct Fields
We can modify fields of a struct in Go by assigning new values to them.
For example,
- Create an instance of the
Person
struct with initial values. - Modify the
Age
field of the struct. - Print the modified struct to the console.
Go Program
package main
import "fmt"
type Person struct {
Name string
Age int
}
func main() {
p := Person{Name: "Alice", Age: 25}
p.Age = 26
fmt.Println(p)
}
Output
{Alice 26}
Example 4: Nested Structs
We can define a struct within another struct in Go.
For example,
- Define a struct named
Address
with fieldsCity
andState
. - Define a struct named
Person
with fieldsName
,Age
, andAddress
. - Create an instance of the
Person
struct with nestedAddress
struct and print it to the console.
Go Program
package main
import "fmt"
type Address struct {
City string
State string
}
type Person struct {
Name string
Age int
Address Address
}
func main() {
p := Person{
Name: "Alice",
Age: 25,
Address: Address{
City: "New York",
State: "NY",
},
}
fmt.Println(p)
}
Output
{Alice 25 {New York NY}}