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

 

posted @   fengbohello  阅读(593)  评论(0编辑  收藏  举报
编辑推荐:
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?
点击右上角即可分享
微信分享提示