基本方法

Go 中的方法就像函式一樣,除了它們有接收器

通常接收器是某種結構或型別。

package main

import (
    "fmt"
)

type Employee struct {
    Name string
    Age  int
    Rank int
}

func (empl *Employee) Promote() {
    empl.Rank++
}

func main() {

    Bob := new(Employee)

    Bob.Rank = 1
    fmt.Println("Bobs rank now is: ", Bob.Rank)
    fmt.Println("Lets promote Bob!")

    Bob.Promote()

    fmt.Println("Now Bobs rank is: ", Bob.Rank)

}

輸出:

Bobs rank now is:  1
Lets promote Bob!
Now Bobs rank is:  2