-
Notifications
You must be signed in to change notification settings - Fork 26
/
methods.go
35 lines (27 loc) · 931 Bytes
/
methods.go
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
35
package main
import "fmt"
type rectangle struct {
width, height int
}
// This area method has a receiver type of *rect.
func (r *rectangle) area() int {
return r.width * r.height
}
// Methods can be defined for either pointer or value receiver types.
// Here’s an example of a value receiver.
func (r rectangle) perim() int {
return 2*r.width + 2*r.height
}
// Methods is a function to illustrate methods in go programming language
func Methods() {
r := rectangle{width: 10, height: 5}
// Here we call the 2 methods defined for our struct.
fmt.Println("area: ", r.area())
fmt.Println("perim: ", r.perim())
rp := &r
fmt.Println("area: ", rp.area())
fmt.Println("perim: ", rp.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.
}