Go:Go Methods and Receiver Functions: OOP Without Classes
Go•Methods & OOP

Go Methods and Receiver Functions: OOP Without Classes

Go does not have classes; methods are defined by attaching receiver parameters to standard functions.

Syntax

func (s *Server) Start() {} func (s Server) Status() string {}

Parameters & Values

Key components and acceptable values for this structure:

ParameterTypeDescription
Pointer Receiver (s *Server)ReceiverAllows method to mutate struct fields and avoids copying.
Value Receiver (s Server)ReceiverOperates on a read-only copy of the struct.

Ready-to-Run Code Example

Executable in Compilra

Run this complete, working example directly without installing Go locally:

package main

import "fmt"

type ServerNode struct {
    Hostname string
    Port     int
    IsOnline bool
}

// Pointer receiver mutates struct in place
func (s *ServerNode) Start() {
    s.IsOnline = true
    fmt.Printf("[NODE] %s:%d started successfully.\n", s.Hostname, s.Port)
}

// Value receiver provides read-only display
func (s ServerNode) GetStatus() string {
    if s.IsOnline {
        return "ONLINE"
    }
    return "OFFLINE"
}

func main() {
    node := ServerNode{Hostname: "node-cluster-01", Port: 8080}
    fmt.Printf("Status: %s\n", node.GetStatus())

    node.Start()
    fmt.Printf("Status: %s\n", node.GetStatus())
}
Expected Output:
Status: OFFLINE
[NODE] node-cluster-01:8080 started successfully.
Status: ONLINE

How It Works: Step-by-Step

  • Lines 12-15: Pointer receiver (s *ServerNode) mutates s.IsOnline in place.
  • Lines 18-23: Value receiver (s ServerNode) reads status safely without mutating.

Key Concepts

  • Use pointer receivers when methods need to mutate struct fields or to avoid large copy costs.
  • Go automatically handles referencing and dereferencing when calling methods.

Common Mistake: Using value receiver expecting field mutations to persist

A value receiver operates on a local copy; changes made inside are lost upon return.

❌ Incorrect
func (s ServerNode) Start() { s.IsOnline = true; } // Does NOT persist!
✅ Correct
func (s *ServerNode) Start() { s.IsOnline = true; } // Persists

Related Go Tutorials & Compiler

Run and test Go on Compilra

Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.

Go Online Compiler