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:
| Parameter | Type | Description |
|---|---|---|
| Pointer Receiver (s *Server) | Receiver | Allows method to mutate struct fields and avoids copying. |
| Value Receiver (s Server) | Receiver | Operates on a read-only copy of the struct. |
Ready-to-Run Code Example
Executable in CompilraRun 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; } // PersistsRelated Go Tutorials & Compiler
Go Interfaces and Struct Embedding (Composition Over Inheritance)
Master implicit interfaces and struct embedding (composition) in Go.
Go Multiple Return Values and Error Handling Signatures
Master Go signature multiple return values, named returns, and the idiomatic (result, error) convention without exceptions.
Go Pointers and Pass-by-Reference (* and &)
Master memory pointers in Go: address-of (&), dereference (*), and mutating function arguments.
Go Online Compiler
Open in Compilra IDE
Run and test Go on Compilra
Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.