0
0
Goprogramming~10 mins

Why methods are used in Go - Visual Breakdown

Choose your learning style9 modes available
Concept Flow - Why methods are used
Define a type
Attach method to type
Create instance of type
Call method on instance
Method uses instance data
Perform action or return result
Methods are functions tied to a type that let us work with that type's data easily and clearly.
Execution Sample
Go
package main
import "fmt"
type Circle struct { radius float64 }
func (c Circle) Area() float64 { return 3.14 * c.radius * c.radius }
func main() {
 c := Circle{5}
 fmt.Println(c.Area())
}
This code defines a Circle type with a method Area that calculates its area, then prints the area of a circle with radius 5.
Execution Table
StepActionVariable/ReceiverValueOutput
1Define type CircleCirclestruct with radius float64
2Define method Area on CircleMethod Areauses receiver c Circle
3Create instance ccCircle{radius:5}
4Call c.Area()c.radius5
5Calculate area3.14 * 5 * 578.5
6Return area valueArea()78.5
7Print area78.5
💡 Program ends after printing the area 78.5
Variable Tracker
VariableStartAfter Step 3After Step 5Final
c.radiusundefined555
Area()undefinedundefined78.578.5
Key Moments - 2 Insights
Why do we attach methods to types instead of just using functions?
Methods let us group behavior with data, making code easier to read and use, as shown in step 2 and 4 where Area is tied to Circle.
How does the method know which data to use?
The method receives the instance (receiver) as 'c', so it uses c.radius from the specific Circle instance, as seen in step 4.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the value of c.radius when Area() is called?
Aundefined
B0
C5
D78.5
💡 Hint
Check Step 4 in the execution table where c.radius is used.
At which step is the area value calculated?
AStep 3
BStep 5
CStep 7
DStep 2
💡 Hint
Look at the Action column for calculation details.
If we change c.radius to 10, what will be the output at Step 7?
A314
B78.5
C100
D50
💡 Hint
Area formula is 3.14 * radius * radius; check variable_tracker for radius.
Concept Snapshot
Methods are functions tied to a type.
They let us work with that type's data easily.
Syntax: func (receiver Type) MethodName() {}
Call with instance.MethodName().
Methods group data and behavior clearly.
Full Transcript
In Go, methods are functions attached to types. This lets us call functions directly on data instances, making code clearer. For example, we define a Circle type with a radius. Then we add an Area method to Circle that calculates the area using the radius. When we create a Circle instance with radius 5 and call Area, it returns 78.5. The method knows which data to use because it receives the instance as a receiver parameter. This groups data and behavior together, improving code organization and readability.