type person struct { name string } func(p person)String()string{ return"the person name is "+ p.name }
在 Go 中,(接收者)类型关联的方法不写在类型结构里面,就像类那样;耦合更加宽松;类型和方法之间的关联由接收者来建立。 Go 语言不像其它面相对象语言一样可以写个类,然后在类里面写一堆方法,但其实**Go语言的方法**很巧妙的实现了这种效果:我们只需要在普通函数前面加个接受者(receiver,写在函数名前面的括号里面),这样编译器就知道这个函数(方法)属于哪个struct了
funcstructTest0601() { a := 2 fmt.Println("valueIntTest:", valueIntTest(a)) //函数的参数为值类型,则不能直接将指针作为参数传递 //fmt.Println("valueIntTest:", valueIntTest(&a)) //compile error: cannot use &a (type *int) as type int in function argument
b := 5 fmt.Println("pointerIntTest:", pointerIntTest(&b)) //同样,当函数的参数为指针类型时,也不能直接将值类型作为参数传递 //fmt.Println("pointerIntTest:", pointerIntTest(b)) //compile error:cannot use b (type int) as type *int in function argument }