GO語言結構體方法跟結構體指針方法的區別
首先,我定了三個接口、一個結構和三個方法:
type DeptModeA interface {Name() stringSetName(name string)}type DeptModeB interface {Relocate(building string, floor uint8)}type Dept struct {name stringbuilding stringfloor uint8Key string}func (self Dept) Name() string {return self.name}func (self Dept) SetName(name string) {self.name = name}func (self *Dept) Relocate(building string, floor uint8) {self.building = buildingself.floor = floor}
而后我寫了一些測試代碼:
dept1 :=Dept{name: "MySohu",building: "Internet",floor: 7}switch v := interface{}(dept1).(type) {case DeptModeFull:fmt.Printf("The dept1 is a DeptModeFull./n")case DeptModeB:fmt.Printf("The dept1 is a DeptModeB./n")case DeptModeA:fmt.Printf("The dept1 is a DeptModeA./n")default:fmt.Printf("The type of dept1 is %v/n", v)}deptPtr1 := &dept1if _, ok := interface{}(deptPtr1).(DeptModeFull); ok {fmt.Printf("The deptPtr1 is a DeptModeFull./n")}if _, ok := interface{}(deptPtr1).(DeptModeA); ok {fmt.Printf("The deptPtr1 is a DeptModeA./n")}if _, ok := interface{}(deptPtr1).(DeptModeB); ok {fmt.Printf("The deptPtr1 is a DeptModeB./n")}
打印出的內容:
The dept1 is a DeptModeA.?The deptPtr1 is a DeptModeFull.?The deptPtr1 is a DeptModeA.?The deptPtr1 is a DeptModeB.
假設T是struct,那么Go里面遵循下面幾個原則:
所以你上面的例子dept1應該是擁有方法:Name和SetName
而&dept1擁有方法:Name、SetName和Relocate
這個就是Go里面在設計方法的時候需要注意Receiver的類型
golang/71061.html">Go語言中結構體方法副本傳參與指針傳參的區別
我們來看個例子:
package mainimport ( "fmt")type B struct { Name string}func(b B) Test1() { fmt.Printf("Test1 addr:%p/n", &b) fmt.Printf("Test1 name:%s/n", b.Name) b.Name = "john"}func(b *B) Test2() { fmt.Printf("Test2 addr:%p/n", b) fmt.Printf("Test2 name:%s/n", b.Name) b.Name = "john"}func main() { b := B{} b.Test1() b.Test1() b.Test2() b.Test2()}
執行后結果如下:
Test1 addr:0xc42000e1e0Test1 name:Test1 addr:0xc42000e1f0Test1 name:Test2 addr:0xc42000e1d0Test2 name:Test2 addr:0xc42000e1d0Test2 name:john
可以看到Test1中打印出b結構體的地址在變化,而Test2中沒有變化,這說明每一次Test1的調用,都是傳入的結構體b的一個副本(拷貝),當在Test1中對內部變量的任何改動,都將會失效(因為下一次訪問的時候傳入的是b結構體新的副本)。而Test2方法作為指針傳參時,每一次傳入的都是b結構體的指針,指向的是同一個結構體,因此地址沒有變化,且對內部變量做改動時,都是改動的b結構體內容。
在Go語言中的這個差別可能是對OOP設計的一個坑,在Go語言中要想實現OOP的設計,在進行方法封裝時,都采用Test2的寫法。
總結
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,如果有疑問大家可以留言交流,謝謝大家對VEVB武林網的支持。
新聞熱點
疑難解答