golang之method

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。

method

Go does not have classes. However, you can define methods on types.

package mainimport (    "fmt"    "math")type Vertex struct {    X, Y float64}func (v Vertex) Abs() float64 {    return math.Sqrt(v.X*v.X + v.Y*v.Y)}func (v *Vertex) Scale(f float64) {    v.X = v.X * f    v.Y = v.Y * f}func (v Vertex) ScaleValue(f float64) {    v.X = v.X * f    v.Y = v.Y * f}func main() {    v := Vertex{3, 4}    fmt.Println(v.Abs())    v.Scale(2)    fmt.Println(v.Abs())    v.ScaleValue(2)    fmt.Println(v.Abs())    p := &v    p.Scale(2)    fmt.Println(p.Abs())}

輸出如下:

5
10
10
20

 

三個注意點:

1. Methods with pointer receivers can modify the value to which the receiver points 。

2. methods with pointer receivers take either a value or a pointer as the receiver when they are called:

var v Vertexv.Scale(5)  // OKp := &vp.Scale(10) // OK

3. methods with value receivers take either a value or a pointer as the receiver when they are called:

var v Vertexfmt.Println(v.Abs()) // OKp := &vfmt.Println(p.Abs()) // OK

interface

package mainimport (    "fmt")type I interface {    M()}type T struct {    S string}func (t *T) M() {    fmt.Println(t.S)}func main() {    var i I    t := T{"hello"}    i = &t    i.M()    v := T{"world"}    i = v    i.M()}

main函數後半段代碼會報錯:cannot use v (type T) as type I in assignment: T does not implement I (M method has pointer receiver)

如果把M的receiver類型改成value:

func (t T) M() {    fmt.Println(t.S)}

main函數的代碼將正常運行。

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.