0
0
Goprogramming~15 mins

Defining methods in Go - Mini Project: Build & Apply

Choose your learning style9 modes available
Defining methods in Go
📖 Scenario: You are creating a simple program to represent a Car with its brand and speed. You want to add a method to the Car that can display its current speed in a friendly message.
🎯 Goal: Build a Go program that defines a Car struct and adds a method DisplaySpeed to it. The method should print the car's brand and speed in a sentence.
📋 What You'll Learn
Create a struct called Car with fields Brand (string) and Speed (int).
Create a variable myCar of type Car with brand "Toyota" and speed 120.
Define a method DisplaySpeed with a receiver of type Car that prints the brand and speed.
Call the DisplaySpeed method on myCar to show the output.
💡 Why This Matters
🌍 Real World
Defining methods on structs is how Go programs model real-world objects with both data and actions, like cars, users, or bank accounts.
💼 Career
Understanding methods and structs is essential for Go developers building backend services, tools, or any software that needs organized data and behavior.
Progress0 / 4 steps
1
Create the Car struct and a variable
Create a struct called Car with fields Brand of type string and Speed of type int. Then create a variable called myCar of type Car with Brand set to "Toyota" and Speed set to 120.
Go
Hint

Use type Car struct { ... } to define the struct. Create myCar with Car{Brand: "Toyota", Speed: 120}.

2
Add a method DisplaySpeed to Car
Define a method called DisplaySpeed with a receiver of type Car. The method should print the message: "The is moving at km/h." using fmt.Printf. Use receiver name c.
Go
Hint

Use func (c Car) DisplaySpeed() to define the method. Use fmt.Printf to print the message with c.Brand and c.Speed.

3
Call the DisplaySpeed method on myCar
Inside the main function, call the DisplaySpeed method on the variable myCar.
Go
Hint

Call the method with myCar.DisplaySpeed() inside main.

4
Print the output
Run the program so it prints the message from the DisplaySpeed method.
Go
Hint

Run the program to see the message printed exactly as: The Toyota is moving at 120 km/h.