SyntaxStudy
Sign Up
Go Defining Structs and Methods
Go Beginner 1 min read

Defining Structs and Methods

A struct is a composite type that groups together fields of different types under a single name. Structs are the primary way to define custom data types in Go. Fields are declared with a name and type inside curly braces, and instances are created using struct literals or the `new` built-in function. Methods are functions with a receiver argument that appears between the `func` keyword and the method name. A value receiver receives a copy of the struct and is suitable for read-only operations, while a pointer receiver receives a pointer to the struct and is required when the method needs to modify the struct's fields or when the struct is large enough that copying would be expensive. Go does not have classes or inheritance, but the combination of structs and methods provides equivalent functionality. By convention, the receiver name is a short abbreviation of the type name (e.g., `p` for `Person`), and all methods of a type should use either value receivers or pointer receivers consistently.
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())
}