type N intfunc(n N)value(){n++fmt.Printf("v:%p,%v\n",&n, n)}func(n *N)pointer(){(*n)++fmt.Printf("v:%p,%v\n", n,*n)}funcmain(){var a N =25a.value()fmt.Printf("a: %p,%v\n",&a,a)a.pointer()fmt.Printf("a: %p,%v\n",&a,a)}
type data struct{sync.Mutexbuf [1024]byte}funcmain(){d := data{}d.Lock()//編譯器會處理為 sync.(*Mutex).Lock() 調用defer d.Unlock()}
方法也有同名隱蔽問題,但利用這種特性,可以實現類似覆蓋(override)操作。
type user struct{}type manager struct{user
}func(user)toString()string{return"user"}func(m manager)toString()string{return m.user.toString()+"; manager"}funcmain(){var m managerprintln(m.toString())println(m.user.toString())}
type N intfunc(n N)test(){fmt.Printf("test.n: %p,%d\n",&n, n)}funcmain(){var n N =25fmt.Printf("main.n: %p, %d\n",&n,n)f1 := N.test // func(n N)f1(n)f2 :=(*N).test // func(n *N)f2(&n)//按方法集中的簽名傳遞正確類型的參數}
type N intfunc(n *N)test(){fmt.Printf("test.n: %p,%d\n", n,*n)}funcmain(){var n N =100p :=&nn++f1 := n.testn++f2 := p.testn++fmt.Printf("main.n:%p, %v\n",p,n)f1()f2()}