1. 程式人生 > >Go方法的結構指標和結構值接收者

Go方法的結構指標和結構值接收者

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()
}