首页 > 解决方案 > 以下代码行是什么意思?

问题描述

有人可以帮助我理解注释的代码行吗?

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)
}

标签: go

解决方案


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)只是调用类型methodmyInt

以下是有关此的一些参考资料。
- https://tour.golang.org/methods/3
- https://gobyexample.com/methods


推荐阅读