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
时间: 2024-11-05 22:36:53