โš™๏ธ

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

1

Ruby: def inside class โ†’ Go: independent func + methods via receivers on structs

2

Ruby: return [a, b] โ†’ Go: multiple return values at syntax level (f64, error)

3

Ruby: *args โ†’ Go: ...int (variadic, just different syntax)

4

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

Use Cases

When converting Ruby's class-based design to Go's struct + method pattern When you need to understand and use the multiple return value error handling pattern

References