🧩 1. Functions
A function in Go is a block of code that performs a task and can optionally return values. It's not associated with any type.
// syntex func functionName(params) returnType { // logic }
// example func add(a int, b int) int { return a + b } result := add(2, 3) // result = 5
- Standalone
- Can be called anywhere in the same package
- No receiver
🧱 2. Methods
A method is a function with a receiver — it is associated with a type (usually a struct).
// syntex func (r ReceiverType) methodName(params) returnType { // logic }
The receiver can be a value or a pointer.
// example type User struct { name string } func (u User) greet() { fmt.Println("Hello,", u.name) }
u := User{name: "Alice"} u.greet() // Output: Hello, Alice
📌 Differences at a Glance
Feature | Function | Method |
---|---|---|
Associated With | None | A type (struct, alias, etc.) |
Syntax | func name() | func (r Type) name() |
Call | name() | variable.name() |
Use Case | General purpose operations | Behaviors/actions tied to specific types |
OOP Concept | Not applicable | Like instance methods in OOP |
🧠Receiver Types: Value vs Pointer
📦 Value Receiver ((u User))
- Method gets a copy.
- Cannot modify original data.
func (u User) setName(name string) { u.name = name // won't affect original }
🧷 Pointer Receiver ((u *User))
- Method gets a reference.
- Can modify the original.
func (u *User) setName(name string) { u.name = name // modifies original }
Go allows calling pointer-receiver methods on values and vice versa (automatic conversion).
// Example : Function vs Method type Rectangle struct { width, height float64 } // Function func area(r Rectangle) float64 { return r.width * r.height } // Method func (r Rectangle) Area() float64 { return r.width * r.height }
Both do the same job, but the method feels more object-oriented.
🧪 When to Use What?
Use Case | Choose... |
---|---|
Independent utility logic | Function |
Logic tied to a specific type | Method |
Want to modify a struct | Pointer method |
Behavior abstraction | Method |
Methods on Non-Struct Types
Go allows defining methods on any named type, even primitives.
type MyInt int func (m MyInt) Double() int { return int(m * 2) } var x MyInt = 5 fmt.Println(x.Double()) // 10
Summary
- Functions = general-purpose, independent code blocks.
- Methods = functions bound to a type, useful for behavior and encapsulation.
- Use pointer receivers to modify values or avoid copying.
- Methods make code more modular, readable, and idiomatic in Go.
Top comments (0)