golang中方法接收者为指针和非指针的区别

package main  
  
import "fmt"  
  
type testint int  
  
//乘2  
func (p *testint) testdouble() int {  
    *p = *p * 2  
fmt.Println("testdouble p = ", *p)  
    return 0  
}  
  
//平方  
func (p testint) testsquare() int {  
    p = p * p  
    fmt.Println("square p = ", p)  
    return 0  
}  
  
func main() {  
    var i testint = 2  
    i.testdouble()  
    fmt.Println("i = ", i)  
    i.testsquare()  
    fmt.Println("i = ", i)  
}  
./hello
testdouble p =  4
i =  4
square p =  16
i =  4

我们可以看到当接收者为指针式,我们可以通过方法改变该接收者的属性,非指针类型不能改变接收者属性。这里的接收者和c++中的this指针有一些相似,我们可以把接受者当作一个class,而这些方法就是类的成员函数,当接收者为指针类型是就是c++中的非const成员函数,为非指针时就是const成员函数,不能通过此方法改变累的成员变量。

package main  
  
import "fmt"  
  
type testint int  
  
//乘2  
func (p *testint) testdouble() int {  
    fmt.Printf("in double p 内存地址:%p
",  p)
    *p = *p * 2  
fmt.Println("testdouble p = ", *p)  
    return 0  
}  
  
//平方  
func (p testint) testsquare() int {  
    fmt.Printf("in square p 内存地址:%p
",  &p)
    p = p * p  
    fmt.Println("square p = ", p)  
    return 0  
}  
  
func main() {  
    var i testint = 2  
    fmt.Printf("i 内存地址:%p
",  &i)
    i.testdouble()  
    fmt.Println("i = ", i)  
    i.testsquare()  
    fmt.Println("i = ", i)  
}  


 

i 内存地址:0x400019e010
in double p 内存地址:0x400019e010
testdouble p =  4
i =  4
in square p 内存地址:0x400019e028
square p =  16
i =  4
原文地址:https://www.cnblogs.com/dream397/p/15038909.html