0
0
Goprogramming~5 mins

Creating struct values in Go

Choose your learning style9 modes available
Introduction

Structs help group related data together. Creating struct values lets you store and use this grouped data easily.

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 your program.
When you want to organize data clearly for easier reading and maintenance.
Syntax
Go
type StructName struct {
    Field1 FieldType1
    Field2 FieldType2
    // ... more fields
}

// Creating a struct value
varName := StructName{
    Field1: value1,
    Field2: value2,
}

Use the field names when creating struct values to avoid confusion.

You can also create struct values without field names, but it's less clear.

Examples
This creates a Person struct with Name "Alice" and Age 30.
Go
type Person struct {
    Name string
    Age  int
}

p := Person{
    Name: "Alice",
    Age:  30,
}
This creates a Point struct with X=10 and Y=20 without using field names.
Go
type Point struct {
    X int
    Y int
}

p := Point{10, 20}
You can also create an empty struct and set fields later.
Go
var p Person
p.Name = "Bob"
p.Age = 25
Sample Program

This program creates a Car struct value and prints its fields.

Go
package main

import "fmt"

type Car struct {
    Brand string
    Year  int
}

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

Always use field names when creating struct values for better clarity.

Struct fields can be accessed and changed using dot notation.

Summary

Structs group related data into one unit.

Create struct values using field names for clarity.

You can set or change fields after creating the struct.