Exercise 1: Structs and Methods in Go

Learn how to use structs (`struct`) and their methods in Go.

What is a Struct (`struct`) in Go?

A struct (`struct`) is a way to group multiple variables under the same type. It is used to model complex objects.

type Person struct {
    Name string
    Age  int
}

Adding Methods to Structs

In Go, you can attach methods to a struct to give it behavior:

func (p Person) Introduce() {
    fmt.Println("Hello, my name is", p.Name, "and I am", p.Age, "years old.")
}

Comparison with Other Languages

Exercise Instructions

package main

import "fmt"

type Person struct {
    Name string
    Age  int
}

func (p Person) Introduce() {
    fmt.Println("Hello, my name is", p.Name, "and I am", p.Age, "years old.")
}

func main() {
    p1 := Person{"Alice", 25}
    p1.Introduce()
}

Expected Output

Hello, my name is Alice and I am 25 years old.

📚 Learn more about structs in Go:

Read the official documentation
Next Exercise →

🚀 Enjoying these exercises? If you find them useful and want to support my work, buying me a coffee would be greatly appreciated! ☕😊


☕ Buy me a coffee