0
0
Goprogramming~5 mins

Defining structs in Go

Choose your learning style9 modes available
Introduction

Structs help you group related information together in one place. They let you create your own types to organize data clearly.

When you want to represent a real-world object like a person or a car with multiple details.
When you need to keep related data together, like a book's title, author, and pages.
When you want to pass multiple values as one unit to functions.
When you want to create a blueprint for data that you will use many times.
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 float64 fields X and Y on one line.
Go
type Point struct {
    X, Y float64
}
This defines a Book struct with three fields to hold book details.
Go
type Book struct {
    Title  string
    Author string
    Pages  int
}
Sample Program

This program defines a Person struct, creates a person named Alice who is 30 years old, and prints the details.

Go
package main

import "fmt"

type Person struct {
    Name string
    Age  int
}

func main() {
    p := Person{Name: "Alice", Age: 30}
    fmt.Println("Name:", p.Name)
    fmt.Println("Age:", p.Age)
}
OutputSuccess
Important Notes

Struct field names should start with uppercase if you want to access them from other packages.

You can create a struct variable using a struct literal with field names.

Structs help keep your data organized and easy to work with.

Summary

Structs group related data into one unit.

Use type and struct keywords to define them.

Access fields using dot notation like variable.FieldName.