AnyCompiler

Methods

A method is a function with a receiver — an extra parameter before the function name that ties it to a specific type. func (r Rectangle) Area() reads like a regular function, but r.Area() can be called directly on any Rectangle value.

package main

import "fmt"

type Rectangle struct {
	Width, Height float64
}

func (r Rectangle) Area() float64 {
	return r.Width * r.Height
}

func main() {
	rect := Rectangle{Width: 10, Height: 5}
	fmt.Println("Area:", rect.Area())
}
Output
Area: 50

Pointer receivers for mutation

A value receiver, like the one above, gets a copy of the struct — changes inside the method don't affect the original. A pointer receiver, func (c *Counter), operates on the actual original value instead, which is how a method can actually modify its receiver's state.

package main

import "fmt"

type Counter struct {
	Value int
}

func (c *Counter) Increment() {
	c.Value++
}

func main() {
	counter := Counter{Value: 0}
	counter.Increment()
	counter.Increment()
	fmt.Println(counter.Value)
}
Output
2

Next: interfaces — Go's implicit, duck-typed way of describing shared behavior.

Practice exercise

Define a struct Circle with field Radius float64. Add a method Area() float64 that returns 3.14159 * c.Radius * c.Radius. Create a Circle with Radius 2, then print circle.Area().