📖 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.
Practice
(1/5)
1. What is the purpose of defining a method with a receiver in Go?
easy
A. To import external packages into the program
B. To create a standalone function unrelated to any type
C. To associate a function with a specific type so it can act on its data
D. To declare a global variable accessible everywhere
Solution
Step 1: Understand what a receiver does
A receiver connects a method to a type, allowing the method to access or modify that type's data.
Step 2: Compare with other options
Options A, B, and C describe unrelated concepts: imports, standalone functions, and global variables.
Final Answer:
To associate a function with a specific type so it can act on its data -> Option C
Quick Check:
Receiver links method to type = D [OK]
Hint: Receiver connects method to type's data [OK]
Common Mistakes:
Thinking methods are standalone functions
Confusing methods with variables
Believing receivers import packages
2. Which of the following is the correct syntax to define a method named Speak for a struct type Dog?
easy
A. func (d Dog) Speak() { }
B. func Speak(d Dog) { }
C. func Dog.Speak() { }
D. func Speak() Dog { }
Solution
Step 1: Recall Go method syntax
Methods use the form: func (receiver Type) MethodName() { }.
Step 2: Match syntax to options
func (d Dog) Speak() { } matches this pattern exactly. func Speak(d Dog) { } is a function, not a method. func Dog.Speak() { } is invalid syntax. func Speak() Dog { } is a function returning Dog, not a method.
Final Answer:
func (d Dog) Speak() { } -> Option A
Quick Check:
Method syntax = func (receiver Type) Name() [OK]
Hint: Method syntax always has receiver in parentheses before name [OK]
Common Mistakes:
Omitting receiver parentheses
Using dot notation in function name
Confusing methods with functions
3. What will be the output of this Go program?
package main
import "fmt"
type Counter struct { value int }
func (c Counter) Increment() {
c.value++
}
func main() {
c := Counter{value: 5}
c.Increment()
fmt.Println(c.value)
}
medium
A. 6
B. 5
C. 0
D. Compilation error
Solution
Step 1: Understand receiver type in Increment method
The method uses a value receiver (c Counter), so it works on a copy of the struct, not the original.
Step 2: Trace the method call and print
Increment increases the copy's value, but original c.value remains 5. So printing c.value outputs 5.
Final Answer:
5 -> Option B
Quick Check:
Value receiver does not modify original = 5 [OK]
Hint: Value receiver copies data; original stays unchanged [OK]
Common Mistakes:
Assuming value receiver changes original data
Confusing pointer and value receivers
Expecting incremented output
4. Identify the error in this method definition:
package main
import "fmt"
type Person struct { name string }
func (p *Person) SetName(newName string) {
p.name = newName
}
func main() {
p := Person{name: "Alice"}
p.SetName("Bob")
fmt.Println(p.name)
}
medium
A. No error; code runs and prints 'Bob'
B. Cannot call method with pointer receiver on value variable
C. Method must return a value
D. Missing import of fmt package
Solution
Step 1: Check pointer receiver usage
In Go, methods with pointer receivers can be called on value variables; Go automatically takes address.
Step 2: Verify imports and method behavior
Code imports fmt, method sets name correctly, so p.name becomes "Bob" and prints it.
Final Answer:
No error; code runs and prints 'Bob' -> Option A
Quick Check:
Pointer receiver works on value variable = B [OK]
Hint: Pointer receiver methods can be called on values directly [OK]
5. You want to define a method Reset for a struct Timer that sets its seconds field to zero. Which receiver type should you use and why?
Options:
A) Pointer receiver, because it modifies the original struct's field
B) Value receiver, because it copies the struct and resets the copy
C) Value receiver, because methods cannot have pointer receivers
D) Pointer receiver, but it cannot modify fields inside the struct
hard
A. Pointer receiver, but it cannot modify fields inside the struct
B. Value receiver, because it copies the struct and resets the copy
C. Value receiver, because methods cannot have pointer receivers
D. Pointer receiver, because it modifies the original struct's field
Solution
Step 1: Understand effect of receiver types on struct modification
Value receivers work on copies, so changes do not affect original struct fields.
Step 2: Choose pointer receiver to modify original
Pointer receivers allow methods to change the original struct's fields, so Reset can set seconds to zero effectively.
Final Answer:
Pointer receiver, because it modifies the original struct's field -> Option D
Quick Check:
Pointer receiver modifies original struct = A [OK]
Hint: Use pointer receiver to change original struct fields [OK]
Common Mistakes:
Using value receiver expecting original change
Believing methods can't have pointer receivers
Thinking pointer receiver can't modify fields
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.