版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/wyy626562203/article/details/83411839
Go方法的结构指针和结构值接收者
1.结构指针接收者,会在方法内部改变该结构内部变量的值;
2.结构值接收者,在方法内部对变量的改变不会影响该结构。
package main
import "fmt"
type test struct
{
name string
}
func (self test) firstTest() {
self.name = "firstTest"
}
func (self *test) secondTest() {
self.name = "secondTest"
}
func main() {
t1 := test{"test"} // 值接收者
t1.firstTest() // 不改变name的值
fmt.Println(t1.name)
t2 := &test{"test"} // 指针接收者
t2.secondTest() // 改变name的值
fmt.Println(t2.name)
}
3.对于指针接收者,调用的是值方法,不会改变结构内的变量值
4.对于值接收者,调用的是指针方法,会改变你的结构内的变量值
package main
import "fmt"
type test struct
{
name string
}
func (self test) firstTest() {
self.name = "firstTest"
}
func (self *test) secondTest() {
self.name = "secondTest"
}
func main() {
t3 := test{"test"} // 值接收者
t3.secondTest() // 改变name的值
fmt.Println(t3.name)
t4 := &test{"test"} // 指针接收者
t4.firstTest() // 不改变name的值
fmt.Println(t4.name)
}
类型 *T 的可调用方法集包含接受者为 *T 或 T 的所有方法集,即调用特定接口方法的接口变量
是一个指针类型,那么方法的接受者可以是值类型也可以是指针类型。类型 T 的可调用方法集包含接受者为 T 的所有方法
package main
import "fmt"
type myinterface interface {
printf()
}
type test1 struct {
name string
}
type test2 struct {
name string
}
func (self *test1) printf() {
fmt.Println(self.name)
}
func (self *test2) printf() {
fmt.Println(self.name)
}
func main() {
var myinterface1 myinterface
myinterface1 = test1{"test1"}
myinterface1.printf()
var myinterface2 myinterface
myinterface2 = test2{"test2"}
myinterface2.printf()
}
编译会报错
# command-line-arguments
.\main.go:18:18: self.num undefined (type *test1 has no field or method num)
.\main.go:22:18: self.num undefined (type *test2 has no field or method num)
.\main.go:27:15: cannot use test1 literal (type test1) as type myinterface in assignment:
test1 does not implement myinterface (printf method has pointer receiver)
.\main.go:31:15: cannot use test2 literal (type test2) as type myinterface in assignment:
test2 does not implement myinterface (printf method has pointer receiver)
修改为
func main() {
var myinterface1 myinterface
myinterface1 = &test1{"test1"}
myinterface1.printf()
var myinterface2 myinterface
myinterface2 = &test2{"test2"}
myinterface2.printf()
}