go - 以下代码行是什么意思?
问题描述
有人可以帮助我理解注释的代码行吗?
package main
import "fmt"
type myInt int
func (a myInt) add(b myInt) myInt {
return a + b
}
func main() {
num1 := myInt(5) // mark - 1
fmt.Println(num1)
num2 := myInt(10) // mark - 2
fmt.Println(num2)
sum := num1.add(num2) // mark - 3
fmt.Println("Sum is", sum)
}
解决方案
type myInt int
func (a myInt) add(b myInt) myInt {
return a + b
}
...
num1 := myInt(5)
num2 := myInt(10)
sum := num1.add(num2)
在这里,type myInt int
定义一个类型就像
type myStruct struct {
...
}
并且num1 := myInt(5)
是定义一个类型的变量myInt
,也可以看成是类型转换。
并且sum := num1.add(num2)
只是调用类型method
。myInt
以下是有关此的一些参考资料。
- https://tour.golang.org/methods/3
- https://gobyexample.com/methods
推荐阅读
- parameter-passing - 如何在 Azure 管道中使用 powershell 命令的输出作为参数?
- php - 为什么更新包时“composer.json”没有更新?
- ngrx - ngrx/data:拥有多个 api 根的最佳方式?
- node.js - 在 NPM 包中使用 ES6+ 语法
- android - 应用链接在三星和小米手机上不起作用
- c - 尽管使用了 fclose(),文件并没有被关闭,因此我不能使用 remove() 函数
- c# - Unity 3d 场景正在加载/未加载
- python - 在网页上托管 Jupyter Notebook Python 应用程序
- python - 有没有办法抓取使用 python 加载的数据
- python - Django - 带有 2 个参数的 URL 模板标签