Go Structs and Methods: An Introduction

Lesson Overview

Hello, there! Today, we’ll dive into Go's core data type: structs. Structs in Go, along with struct methods, serve a role similar to classes in object-oriented programming. We'll explore structs, how they encapsulate data, and how we can manipulate this data using methods.

Go Structs Refresher

To fully grasp Go's structs, think of them as blueprints for creating complex data types by grouping different pieces of related information. Unlike arrays or slices, which hold data of the same type, structs allow you to mix various data types. This powerful feature is why they're akin to custom records or tailored objects, making them very versatile in developing sophisticated programs.

In addition to organizing your data, structs are instrumental in modularizing your code and breaking down complex programs into manageable pieces. This enhances code reusability and readability, providing a clear way to model real-life entities—just like how a GameCharacter may have fields for attributes like health and strength.

Defining Go Structs

In Go, to define a struct, use the type keyword followed by the struct name and its fields. For instance, considering the GameCharacter example:

package main

import "fmt"

// GameCharacter struct definition
type GameCharacter struct {
    name     string
    health   int
    strength int
}

Struct Fields

Fields in Go structs hold data related to each struct instance, like the name, health, and strength in the GameCharacter struct. Initialize fields by passing values as a composite literal or explicitly setting them after creation.

package main

import "fmt"

// GameCharacter struct with fields
type GameCharacter struct {
    name     string
    health   int
    strength int
}

func main() {
    // Initialize fields using composite literal
    character := GameCharacter{name: "Hero", health: 100, strength: 20}
    fmt.Println(character.name)    // prints: Hero
    fmt.Println(character.health)  // prints: 100
    fmt.Println(character.strength) // prints: 20

    // Update field values
    character.health = 90
    fmt.Println(character.health)  // prints: 90
}

Accessing struct fields involves the dot (.) operator, and initialization occurs using composite literals or individual assignments.

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal