Go
Beginner
1 min read
Defining Structs and Methods
Example
package main
import (
"fmt"
"math"
)
type Point struct {
X, Y float64
}
// Value receiver — does not modify the struct
func (p Point) Distance(q Point) float64 {
dx := p.X - q.X
dy := p.Y - q.Y
return math.Sqrt(dx*dx + dy*dy)
}
type Rectangle struct {
TopLeft Point
BottomRight Point
}
// Pointer receiver — modifies the struct
func (r *Rectangle) Scale(factor float64) {
r.BottomRight.X = r.TopLeft.X + (r.BottomRight.X-r.TopLeft.X)*factor
r.BottomRight.Y = r.TopLeft.Y + (r.BottomRight.Y-r.TopLeft.Y)*factor
}
func (r Rectangle) Area() float64 {
w := r.BottomRight.X - r.TopLeft.X
h := r.BottomRight.Y - r.TopLeft.Y
return w * h
}
func main() {
p1 := Point{0, 0}
p2 := Point{3, 4}
fmt.Printf("Distance: %.2f\n", p1.Distance(p2))
rect := Rectangle{
TopLeft: Point{0, 0},
BottomRight: Point{10, 5},
}
fmt.Printf("Area before: %.2f\n", rect.Area())
rect.Scale(2)
fmt.Printf("Area after scale(2): %.2f\n", rect.Area())
}