github.com/aykevl/tinygo@v0.5.0/testdata/calls.go (about)

     1  package main
     2  
     3  type Thing struct {
     4  	name string
     5  }
     6  
     7  func (t Thing) String() string {
     8  	return t.name
     9  }
    10  
    11  func (t Thing) Print(arg string) {
    12  	println("Thing.Print:", t.name, "arg:", arg)
    13  }
    14  
    15  type Printer interface {
    16  	Print(string)
    17  }
    18  
    19  func main() {
    20  	thing := &Thing{"foo"}
    21  
    22  	// function pointers
    23  	runFunc(hello, 5) // must be indirect to avoid obvious inlining
    24  
    25  	// deferred functions
    26  	testDefer()
    27  
    28  	// Take a bound method and use it as a function pointer.
    29  	// This function pointer needs a context pointer.
    30  	testBound(thing.String)
    31  
    32  	// closures
    33  	func() {
    34  		println("thing inside closure:", thing.String())
    35  	}()
    36  	runFunc(func(i int) {
    37  		println("inside fp closure:", thing.String(), i)
    38  	}, 3)
    39  }
    40  
    41  func runFunc(f func(int), arg int) {
    42  	f(arg)
    43  }
    44  
    45  func hello(n int) {
    46  	println("hello from function pointer:", n)
    47  }
    48  
    49  func testDefer() {
    50  	i := 1
    51  	defer deferred("...run as defer", i)
    52  	i++
    53  	defer func() {
    54  		println("...run closure deferred:", i)
    55  	}()
    56  	i++
    57  	defer deferred("...run as defer", i)
    58  	i++
    59  
    60  	var t Printer = &Thing{"foo"}
    61  	defer t.Print("bar")
    62  
    63  	println("deferring...")
    64  }
    65  
    66  func deferred(msg string, i int) {
    67  	println(msg, i)
    68  }
    69  
    70  func testBound(f func() string) {
    71  	println("bound method:", f())
    72  }