-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmethods.go
More file actions
34 lines (26 loc) · 766 Bytes
/
Copy pathmethods.go
File metadata and controls
34 lines (26 loc) · 766 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
package main
import "fmt"
type rect struct {
width, height int
}
// The 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. Here is a value receiver.
func (r rect) perim() int {
return 2*r.width + 2*r.height
}
func main() {
r := rect{width: 10, height: 5}
fmt.Println("area: ", r.area())
fmt.Println("perim: ", r.perim())
// Go automatically handles conversion between values and
// pointers for method calls. You may want to use a pointer
// receiver type to avoid copying on method calls or to allow
// the method to mutate the receiving struct.
rp := &r
fmt.Println("area: ", rp.area())
fmt.Println("perim: ", rp.perim())
}