Lesson 11 of 18

Structs and Methods

Custom Types

Structs are Go's way of grouping related data. If you are coming from an object-oriented language, structs are the closest thing to classes, but without inheritance.

Defining a Struct

type Point struct {
    X float64
    Y float64
}

Every starship in the fleet has a spec sheet: name, class, warp factor, crew complement. A Go struct is essentially the same thing --- a blueprint that groups all the critical data in one place.

Creating Instances

// Named fields (preferred for clarity)
p1 := Point{X: 1.0, Y: 2.0}

// Positional (fragile, avoid unless struct is tiny)
p2 := Point{1.0, 2.0}

// Zero value (all fields are zero-valued)
var p3 Point // {0, 0}

Methods

Methods are functions attached to a type. They are declared with a receiver between the func keyword and the method name:

func (p Point) Distance() float64 {
    return math.Sqrt(p.X*p.X + p.Y*p.Y)
}

Call methods with dot notation:

p := Point{X: 3, Y: 4}
fmt.Println(p.Distance()) // 5

Pointer Receivers

A value receiver gets a copy of the struct. A pointer receiver gets a reference and can modify the original:

func (p *Point) Scale(factor float64) {
    p.X *= factor
    p.Y *= factor
}

Use a pointer receiver when:

  • The method needs to modify the struct
  • The struct is large and copying would be expensive
  • You want consistency (if any method uses a pointer receiver, all should)

Go automatically handles the conversion: you can call a pointer-receiver method on a value, and vice versa.

Your Task

Define a Rect struct with fields Width and Height (both float64).

Add two methods:

  • Area() returns the area (Width * Height)
  • Perimeter() returns the perimeter (2 * (Width + Height))
Go runtime loading...
Loading...
Click "Run" to execute your code.