当前位置:网站首页>GO函数的使用
GO函数的使用
2022-04-21 10:42:00 【genispan】
熟悉Go函数的语法结构
因为GO没有类的概念,所以使用结构体来模拟。代码中的函数分别计算两个整数的平方根和取数值的绝对值。
package main
import (
"fmt"
"math"
)
type MyFloat float64
type Vertex struct {
X, Y float64
}
//Vertex指针对应的Abs方法
func (v *Vertex) Abs() float64 {
return math.Sqrt(v.X*v.X + v.Y*v.Y)
}
//MyFloat结构体对应的Abs方法
func (f MyFloat) Abs() float64 {
if f < 0 {
return float64(-f)
}
return float64(f)
}
func main() {
v := &Vertex{6, 4} //获取Vertex结构体的指针
fmt.Println(v.Abs())
f := MyFloat(-math.Sqrt2) //取2的平方根
fmt.Println("float Abs=", f.Abs())
}
此处定义对应的方法的意义在于操作的是原始对象。如果定义为结构体类型对应的方法,则表示传递的参数为结构体的一个副本,而不是原始对象。我们可以添加Add方法,如下所示:
package main
import (
"fmt"
"math"
)
type MyFloat float64
type Vertex struct {
X, Y float64
}
//Vertex指针对应的Abs方法
func (v *Vertex) Abs() float64 {
return math.Sqrt(v.X*v.X + v.Y*v.Y)
}
//Vertex指针对应的Add方法
func (v *Vertex) Add(f float64) {
v.X += f
v.Y += f
}
//MyFloat结构体对应的Abs方法
func (f MyFloat) Abs() float64 {
if f < 0 {
return float64(-f)
}
return float64(f)
}
func main() {
v := &Vertex{6, 4} //获取Vertex结构体的指针
fmt.Println(v.Abs())
v.Add(3.14)
fmt.Println(v)
f := MyFloat(-math.Sqrt2) //取2的平方根
fmt.Println("float Abs=", f.Abs())
}
运行之后,对象v内部的X和Y的值被改变了。
版权声明
本文为[genispan]所创,转载请带上原文链接,感谢
https://blog.csdn.net/genispan/article/details/42496507
边栏推荐
- Basic commands of MySQL
- 24张图攻克border-image
- shell脚本修改文件名和权限
- Filebeat收集日志数据传输到Redis,通过Logstash来根据日志字段创建不同的ES索引
- Vulnhub PRIME: 1
- Page navigation - declarative / programmatic navigation
- Uniapp wechat applet clicks the button to call wechat payment
- Local IP addresses are accessed using domain names
- TypeError: The view function did not return a valid response. The function either returned none
- 搭建个人主页保姆级教程(一)
猜你喜欢

桶排序 ← C语言实现

本地IP地址使用域名访问

英伟达、万向、风语筑、追梦者基金……大咖漫谈“元宇宙与产业新机遇”丨2022元宇宙云峰会...

ConvBERT: Improving BERT with Span-based Dynamic Convolution论文的阅读笔记

Read the meaning of seek tiger's launch of Genesis node

Pytorch学习笔记(3)torch.autograd,逻辑回归模型训练

浏览器插件(BD新标签页)壁纸鉴赏

如何阅读一份源代码?

Local IP addresses are accessed using domain names

Mysql 002 DDL
随机推荐
微信公众号网页分享设置及问题
canvas 学习笔记
What happens when you run the NPM install command?
2-3. 注册selector
Laravel Redis的使用
zsh: segmentation fault 解决方法
What is the future development prospect of automated operation and maintenance platform?
bash shell中的退出状态码
MKL and vs2019 configuration method
What is a timestamp?
Showcase时手机不够怎么办? 云真机平台atxserver2
2-3. Register selector
【acwing】1459. 奶牛体操(模拟、思维)
Convbert: improving Bert with span based dynamic revolution
伦敦金在哪里开户安全?
Digital Economy & Green Innovation matching: Green Patent matching data of digital finance enterprises of 3169 companies in China, 2011-2019
24张图攻克border-image
How to write product requirements document (PRD) with the idea of five elements of user experience
MKL and vs2019 configuration method
2022 information and future preparation 1 new online judge 1112: plane segmentation