Introduction
Methods let us attach actions to specific data types. This helps organize code and makes it easier to work with related data and behavior together.
Methods let us attach actions to specific data types. This helps organize code and makes it easier to work with related data and behavior together.
func (receiver Type) MethodName(params) returnType {
// method body
}The receiver is like a nickname for the data the method works on.
Methods are similar to functions but are tied to a specific type.
Greet belongs to the Person type and returns a greeting.func (p Person) Greet() string {
return "Hello, " + p.Name
}*Counter to change the original data.func (c *Counter) Increment() {
c.Value++
}This program defines a Person type with a method Greet. It prints a greeting using the person's name.
package main import "fmt" type Person struct { Name string } func (p Person) Greet() string { return "Hello, " + p.Name } func main() { person := Person{Name: "Alice"} fmt.Println(person.Greet()) }
Using pointer receivers lets methods modify the original data.
Methods help keep code organized and easier to read.
Methods connect actions to specific data types.
They help organize and reuse code.
Pointer receivers allow methods to change data.
package main
import "fmt"
type Counter struct {
value int
}
func (c *Counter) Increment() {
c.value++
}
func main() {
c := Counter{value: 5}
c.Increment()
fmt.Println(c.value)
}type Rectangle struct {
width, height int
}
func (r Rectangle) Scale(factor int) {
r.width = r.width * factor
r.height = r.height * factor
}Pass the test and this pattern moves unknown