翻译自 https://gobyexample.com/
Go by Example
Go is an open source programming language designed for building simple, fast, and reliable software.
Go by Example is a hands-on introduction to Go using annotated example programs. Check out the first example or browse the full list below.
Go by Example: Methods
golang支持在结构体上定义方法。
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
| package main
import "fmt"
type rect struct { width, height int }
func (r *rect) area() int { return 2*r.width * 2*r.height }
funv (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())
rp := &r fmt.Println("area: ", rp.area()) fmt.Println("perim: ", rp.perim()) }
|
1 2 3 4 5
| $ go run methods.go area: 50 perim: 30 area: 50 perim: 30
|
原文链接:Go by Example: Methods