定义函数接收者
package main
import (
"fmt"
)
type A struct {
Name string
}
type B struct {
Name string
}
func main() {
a := A{}
a.print()
fmt.Println(a.Name)
b := B{}
b.print()
fmt.Println(b.Name)
}
//这里定义了函数的接收者
func (a *A) print() {
a.Name = "AA"
fmt.Println("A")
}
func (b B) print() {
b.Name = "BB"
fmt.Println("B")
}
给 int 添加方法(方法绑定必须在相同包中)
package main
import "fmt"
type Test int
func main() {
var a Test
a.print()
}
func (test Test) print() {
fmt.Println("test")
}
Method Values 和 Method Expressions
package main
import "fmt"
type Test int
func main() {
var a Test
//Method Values
a.print()
// Method Expressions
(*Test).print(&a)
}
func (test *Test) print() {
fmt.Println("test")
}
给自定义类型添加方法
package main
import "fmt"
type Test int
func main() {
var a Test
a.increase(10)
fmt.Println(a)
}
func (test *Test) increase(num Test) {
*test += num
}