Menu
Coddy logo textTech

Structs as Classes

Part of the Object Oriented Programming section of Coddy's GO journey — lesson 6 of 107.

Structs in Go serve the same purpose as classes in other languages. They bundle related data together into a single type.

Define a struct with multiple field types

type Car struct {
    Brand string
    Model string
    Year  int
    Price float64
}

Create an instance using field names

car := Car{
    Brand: "Toyota",
    Model: "Camry",
    Year:  2023,
    Price: 28000.50,
}

Access and modify fields

fmt.Println(car.Brand) // Toyota
fmt.Println(car.Year)  // 2023

car.Price = 27000.00   // Modify a field
fmt.Println(car.Price) // 27000

Structs can contain other structs

type Engine struct {
    Horsepower int
    FuelType   string
}

type Car struct {
    Brand  string
    Model  string
    Engine Engine
}

car := Car{
    Brand:  "Ford",
    Model:  "Mustang",
    Engine: Engine{Horsepower: 450, FuelType: "Gasoline"},
}
fmt.Println(car.Engine.Horsepower) // 450

Structs group related fields together. You access fields with the dot operator, and you can nest structs inside other structs to build complex data models.

challenge icon

Challenge

Medium

Define a Profile struct with the following fields:

  • Name — string
  • Email — string
  • Age — int
  • Role — string

Cheat sheet

Structs in Go bundle related data together into a single type, similar to classes in other languages.

Define a struct with multiple field types:

type Car struct {
    Brand string
    Model string
    Year  int
    Price float64
}

Create an instance using field names:

car := Car{
    Brand: "Toyota",
    Model: "Camry",
    Year:  2023,
    Price: 28000.50,
}

Access and modify fields using the dot operator:

fmt.Println(car.Brand) // Toyota
car.Price = 27000.00   // Modify a field

Structs can contain other structs (nested structs):

type Engine struct {
    Horsepower int
    FuelType   string
}

type Car struct {
    Brand  string
    Model  string
    Engine Engine
}

car := Car{
    Brand:  "Ford",
    Model:  "Mustang",
    Engine: Engine{Horsepower: 450, FuelType: "Gasoline"},
}
fmt.Println(car.Engine.Horsepower) // 450

Try it yourself

package main

import "fmt"

func main() {
    var name, email, role string
    var age int
    fmt.Scan(&name, &email, &age, &role)

    p := Profile{
        Name:  name,
        Email: email,
        Age:   age,
        Role:  role,
    }

    fmt.Printf("Name: %s\n", p.Name)
    fmt.Printf("Email: %s\n", p.Email)
    fmt.Printf("Age: %d\n", p.Age)
    fmt.Printf("Role: %s\n", p.Role)
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Object Oriented Programming