Methods
package main
import "fmt"
// Define a struct named 'rect' with two fields: 'width' and 'height'
type rect struct {
width, height int
}
// Method with a pointer receiver: 'area' calculates and returns the area of the rectangle
func (r *rect) area() int {
return r.width * r.height
}
// Method with a value receiver: 'perim' calculates and returns the perimeter of the rectangle
func (r rect) perim() int {
return 2*r.width + 2*r.height
}
func main() {
// Create an instance of the 'rect' struct with field values 10 and 5
r := rect{width: 10, height: 5}
// Call the 'area' method on the struct and print the result
fmt.Println("area: ", r.area()) // Output: area: 50
// Call the 'perim' method on the struct and print the result
fmt.Println("perim:", r.perim()) // Output: perim: 30
// Create a pointer to the 'rect' struct
rp := &r
// Call the 'area' method using a pointer receiver and print the result
fmt.Println("area: ", rp.area()) // Output: area: 50
// Call the 'perim' method using a value receiver through the pointer and print the result
fmt.Println("perim:", rp.perim()) // Output: perim: 30
}Output
Last updated