initial commit
This commit is contained in:
commit
493ce92e02
62 changed files with 1213 additions and 0 deletions
BIN
methods/methods
Executable file
BIN
methods/methods
Executable file
Binary file not shown.
34
methods/methods.go
Normal file
34
methods/methods.go
Normal file
|
|
@ -0,0 +1,34 @@
|
|||
package main
|
||||
|
||||
import "fmt"
|
||||
|
||||
type rect struct {
|
||||
width, height int
|
||||
}
|
||||
|
||||
//this area method has a reciever type of *rect
|
||||
func (r *rect) area() int {
|
||||
return r.width * r.height
|
||||
}
|
||||
|
||||
// Methods can be defined for either pointer or value reciever types
|
||||
// heres an example of a value receiver
|
||||
func (r rect) perim() int {
|
||||
return 2*r.width + 2*r.height
|
||||
}
|
||||
|
||||
func main() {
|
||||
r := rect{width:10,height:5}
|
||||
|
||||
//here we call the two methods defined for our struct
|
||||
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())
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue