GO语言练习:struct基础练习
1、代码
2、运行
1、代码
1 package main 2 3 import "fmt" 4 5 type Rect struct { 6 x, y float64 7 width, height float64 8 } 9 10 func (r * Rect) Area() float64 { 11 return r.width * r.height 12 } 13 14 func Init() { 15 rect1 := new(Rect) 16 rect2 := &Rect{} 17 rect3 := &Rect{0, 0, 100, 200} 18 rect4 := &Rect{width : 100, height : 200} 19 20 ShowRect(rect1) 21 ShowRect(rect2) 22 ShowRect(rect3) 23 ShowRect(rect4) 24 } 25 func NewRect(x, y, width, height float64) * Rect { 26 return &Rect{x, y, width, height} 27 } 28 29 func ShowRect(rect * Rect) { 30 fmt.Println(rect.x, rect.y, rect.width, rect.height) 31 } 32 33 func main() { 34 Init() 35 var rect *Rect = NewRect(1.0, 2.0, 3.0, 4.0) 36 ShowRect(rect) 37 fmt.Println("area = ", rect.Area()) 38 }
2、运行
$ go run struct.go 0 0 0 0 0 0 0 0 0 0 100 200 0 0 100 200 1 2 3 4 area = 12
作 者:fengbohello
个人网站:http://www.fengbohello.top/
E-mail : fengbohello@foxmail.com
欢迎转载,转载请注明作者和出处。
因作者水平有限,不免出现遗漏和错误。希望热心的同学能够帮我指出来,我会尽快修改。愿大家共同进步,阿里嘎多~