方法就相当于类的行为,对应于固定的结构体
package main
import "fmt"
type A struct{
Name string
}
type B struct{
Name string
}
func (a A)Print(){
fmt.Println("A")
}
func (b B)Print(){
fmt.Println("B")
}
func main(){
a:=A{}
a.Print()//achieve the method of struct A
b:=B{}
b.Print()//thougth the name is same it will not make trouble
}
通过a.Print和b.Print那么就是针对不同类型的所以可以分辨
但是如果加一个
func (b B)Print(int){
fmt.Println("B")
}
因为没有重载功能它并不能够区分应该使用那么一个函数
要在receiver中改变值也应该使用指针
试试看类型别名能否添加method
package main
import "fmt"
type TZ int
func (a *TZ)Print(){
fmt.Println("A")
}
func main(){
var a TZ//though the bottom of the TZ is int we still can append method
a.Print()
}
这更加证明了虽然是别名但是到底还是不同,因为内置类型如int等就无法添加方法
方法只能对当前包的类型进行绑定
method-value和method-expression
package main
import "fmt"
type TZ int
func (a *TZ)Print(){
fmt.Println("A")
}
func main(){
var a TZ
a.Print()//method value
(*TZ).Print(&a)//method expression
}
方法的权限问题
package main
import "fmt"
type A struct{
name string//private if 'n' public if 'N'
}
//private and public is for package only the Name can be used in other package
func (a *A)Print(){
a.name="123"
fmt.Println(a.name)
}
func main(){
a:=A{}
a.Print()
fmt.Println(a.name)
}
声明:
m map[interface{}]bool
选择类型为interface{}是有原因的,因为这样可以保证元素可以是任何类型的