0
0
Goprogramming~5 mins

Struct usage patterns in Go

Choose your learning style9 modes available
Introduction

Structs help you group related data together in one place. They make your code organized and easy to understand.

When you want to represent a real-world object like a person or a car with multiple details.
When you need to pass multiple related values together in functions.
When you want to create reusable blueprints for data with different values.
When you want to group settings or configurations in one variable.
When you want to improve code readability by naming groups of data.
Syntax
Go
type StructName struct {
    Field1 FieldType1
    Field2 FieldType2
    // more fields
}

Use type keyword to define a new struct type.

Each field has a name and a type, separated by space.

Examples
This defines a Person struct with two fields: Name and Age.
Go
type Person struct {
    Name string
    Age  int
}
This defines a Point struct with two integer fields X and Y on one line.
Go
type Point struct {
    X, Y int
}
This creates a new Person value with Name set to "Alice" and Age set to 30.
Go
p := Person{Name: "Alice", Age: 30}
This declares a Person variable and sets its fields one by one.
Go
var p Person
p.Name = "Bob"
p.Age = 25
Sample Program

This program shows how to define a Car struct, create values, and access their fields.

Go
package main

import "fmt"

type Car struct {
    Brand string
    Year  int
}

func main() {
    myCar := Car{Brand: "Toyota", Year: 2020}
    fmt.Println("My car brand is", myCar.Brand)
    fmt.Println("It was made in", myCar.Year)

    var oldCar Car
    oldCar.Brand = "Ford"
    oldCar.Year = 1995
    fmt.Println("Old car brand:", oldCar.Brand)
    fmt.Println("Old car year:", oldCar.Year)
}
OutputSuccess
Important Notes

You can create structs with or without field names when initializing.

Structs can be nested inside other structs for complex data.

Use pointers to structs if you want to modify the original data inside functions.

Summary

Structs group related data with named fields.

Use structs to model real-world things or organize data.

You can create, access, and modify struct fields easily.