go by example part 2

This commit is contained in:
2022-01-01 19:47:24 +01:00
parent afe165089d
commit c1b7c64da2
10 changed files with 335 additions and 0 deletions

View File

@@ -0,0 +1,32 @@
// methods defined on struct types
package main
import "fmt"
type rect struct {
width, height int
}
// area method has a receiver type of *rect
func (r *rect) area() int {
return r.width * r.height
}
// Methods can be defined for either pointer or value receiver types
func (r rect) perim() int {
return 2*r.width + 2*r.height
}
func main() {
r := rect{width: 10, height: 5}
// call 2 methods defined for the struct
fmt.Println("area: ", r.area())
fmt.Println("perim:", r.perim())
// Go automatically handles conversion between values and pointers for method calls
rp := &r
fmt.Println("area: ", rp.area())
fmt.Println("perim:", rp.perim())
}