Sep 19, 2018

[Go] method expressions

Something seldom use but interesting...
golang's method expression, a bit smells like C++ std::bind ....


package main

import (
 "fmt"
 "reflect"
)

type Fun struct {
 A int
}

func (f Fun) run() {
 fmt.Println(f.A)
}

func (f *Fun) runWithPtr() {
 fmt.Println(f.A)
}

func main() {
 var f = Fun.run              // Method expression
 var fptr = (*Fun).runWithPtr // Method expression

 f(Fun{42})                   // Passing in this object
 fptr(&Fun{38})               // Passing in this ptr

 fmt.Println(reflect.TypeOf(f))  // type has this
 fmt.Println(reflect.TypeOf(fptr))  // this has this ptr
 //-------------
 var bindf = Fun{43}.run
// With escape analysis, there's no pr-value, x-value,
// no more thinking about stack/heap, lifetime of an type instance etc.
// Good or Bad? :-P
 var bindfPtr = (&Fun{39}).runWithPtr 

 bindf()
 bindfPtr()

 fmt.Println(reflect.TypeOf(bindf)) // type has no this
 fmt.Println(reflect.TypeOf(bindfPtr)) // type has no this ptr
}

print out:
42
38
func(main.Fun)
func(*main.Fun)
43
39
func()
func()

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.