Go语言方法规则:隐式传递调用

    /    2019-02-28

根据调用者不同,方法分为两种表现形式:方法(method value)、方法表达式(method expression)。

两者都可像普通函数那样赋值和传参,区别在于 方法 (method value)绑定了实例,而方法表达式(method expression)必须显式传参。

隐式传递调用

接受者隐式传递,类型 T 和 *T 上的方法集是互相继承的。

package main

import (
    "fmt"
)

type T struct {
    string
}

func (t T) testT() {
    fmt.Println("接受者为 T ")
}

func (t *T) testP() {
    fmt.Println("接受者为 *T ")
}

func main() {
    t := T{"oldboy"}
    methodValue1 := t.testT
    methodValue1()
    methodValue2 := (&t).testT
    methodValue2()
    methodValue3 := t.testP
    methodValue3()
    methodValue4 := (&t).testP
    methodValue4()
}

接受者隐式传递,类型 S 包含匿名字段 *T 或 T ,则 S 和 *S 方法集包含 T 和 *T 上的方法集是互相继承的。

package main

import (
    "fmt"
)

type ST struct {
    T
}

type SP struct {
    *T
}

type T struct {
    string
}

func (t T) testT() {
    fmt.Println("类型 S 包含匿名字段 *T 或 T ,则 S 和 *S 方法集包含 T 方法")
}
func (t *T) testP() {
    fmt.Println("类型 S 包含匿名字段 *T 或 T ,则 S 和 *S 方法集包含 *T 方法")
}

func main() {
    st1 := ST{T{"oldboy"}}
    methodValue1 := st1.testT
    methodValue1()
    methodValue2 := (&st1).testT
    methodValue2()
    methodValue3 := st1.testP
    methodValue3()
    methodValue4 := (&st1).testP
    methodValue4()

    sp1 := SP{&T{"oldboy"}}
    methodValue5 := sp1.testT
    methodValue5()
    methodValue6 := (&sp1).testT
    methodValue6()
    methodValue7 := sp1.testP
    methodValue7()
    methodValue8 := (&sp1).testP
    methodValue8()
}


(0)

分享至