Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Go function calls #9

Open
katsusan opened this issue Aug 8, 2020 · 0 comments
Open

Go function calls #9

katsusan opened this issue Aug 8, 2020 · 0 comments

Comments

@katsusan
Copy link
Owner

katsusan commented Aug 8, 2020

Go里一共有4种函数:

  • top-level func
  • method with value receiver
  • method with pointer receiver
  • func literal

调用的方式有5种:

  • direct call of top-level func
  • direct call of method with value receiver
  • direct call of method with pointer receiver
  • indirect call of func value
  • indirect call of method on interface
package main


func TopLevel(x int) {}


type Pointer struct{}
func (*Pointer) M(int) {}


type Value struct{}
func (Value) M(int) {}

type Interface interface { M(int) }

var literal = func(x int) {}


func main() {

        // direct call of top-level func
        TopLevel(1)

        // direct call of method with value receiver (two spellings, but same)
        var v Value
        v.M(1)
        Value.M(v, 1)

        // direct call of method with pointer receiver (two spellings, but same)
        var p Pointer
        (&p).M(1)
        (*Pointer).M(&p, 1)
       
        // indirect call of func value (×4)
        f1 := TopLevel
        f1(1)

        f2 := Value.M
        f2(v, 1)

        f3 := (*Pointer).M
        f3(&p, 1)

        f4 := literal
        f4(1)

        // indirect call of method on interface (×3)
        var i Interface
        i = v
        i.M(1)

        i = &v
        i.M(1)

        i = &p
        i.M(1)

        Interface.M(i, 1)
        Interface.M(v, 1)
        Interface.M(&p, 1)
}

综上,总共有10种函数与调用方式的组合:

  • direct call of top-level func /
  • direct call of method with value receiver /
  • direct call of method with pointer receiver /
  • indirect call of func value / set to top-level func
  • indirect call of func value / set to value method
  • indirect call of func value / set to pointer method
  • indirect call of func value / set to func literal
  • indirect call of method on interface / containing value with value method
  • indirect call of method on interface / containing pointer with value method
  • indirect call of method on interface / containing pointer with pointer method

//refer: https://docs.google.com/document/d/1bMwCey-gmqZVTpRax-ESeVuZGmjwbocYs1iHplK-cjo/pub

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant