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

 

相关文章:

  • 2021-12-09
  • 2021-05-05
  • 2021-10-08
  • 2021-07-06
  • 2021-12-17
  • 2021-11-20
  • 2021-12-19
  • 2022-01-01
猜你喜欢
  • 2021-09-24
  • 2021-11-20
  • 2021-11-29
  • 2021-11-20
  • 2021-11-21
  • 2021-11-28
  • 2021-12-27
  • 2021-11-11
相关资源
相似解决方案