Functions & Methods โ Methods in a Classless World
Ruby's def lives inside classes. Go's func attaches to structs.
In Ruby, methods always live inside a class. class User; def name; end; end โ methods belong to classes.
In Go, functions are the default. func add(a, b int) int { return a + b } โ independent functions belonging to no type. In Ruby you'd make these with module_function, but in Go this is the default.
Methods = Functions with a Receiver
Go methods are just functions with a "receiver":
type User struct { Name string }
func (u User) Greet() string { return "Hi, " + u.Name }
(u User) is the receiver. Think of it as self being explicitly declared. In Ruby, def greet; "Hi, #{name}"; end has an implicit self.
Multiple Return Values
Ruby returns multiple values via arrays: return [value, error]. Go supports multiple returns at the syntax level: func divide(a, b float64) (float64, error). This is the foundation of Go's error handling pattern.
Variadic Arguments
Ruby's def sum(*numbers) โ Go's func sum(numbers ...int) int. Different syntax, same concept. But ... comes before the type in Go, while * comes before the parameter in Ruby.
First-Class Functions
Ruby has Proc, Lambda, blocks. Go has first-class functions too โ assign functions to variables, pass them as arguments. But there's no implicit block-passing syntax like Ruby. Always explicit.
Ruby to Go
Ruby: def inside class โ Go: independent func + methods via receivers on structs
Ruby: return [a, b] โ Go: multiple return values at syntax level (f64, error)
Ruby: *args โ Go: ...int (variadic, just different syntax)
Ruby: Proc/Lambda/Block โ Go: first-class functions but no block syntax
Pros
- ✓ Receiver syntax makes self explicit โ clear which type the method belongs to
- ✓ Multiple returns make error handling natural โ error propagation without exceptions
Cons
- ✗ No class inheritance โ Ruby's < inheritance pattern must be replaced with struct embedding
- ✗ No block/yield pattern โ hard to write DSL-style code like Ruby