Functions and Methods

Table of Contents

Basics of func tutorial

func add(x int, y int) int {
    return x + y
}

// Declarations of consecutive same type parameters can be coalesced.
func add(x, y int) int {
    return x + y
}

// Return values can be named, in which case
// the name declares a local variable initialized to the zero value for its type.
func add(x, y int) (z int) {
    z = x + y
    return  // this is called 'naked(or bare) return'
}

// Functions can have multiple return values
func addsub(x, y int) (int, int) {
    return x + y, x - y
}
Deferred functions
4 3 2 1 0
Variadic functions; within the body of the function, the type of vals is an []int slice.
Place ... after the final argument to call a function with elements of a slice.
Methods
It is possible to call methods of embedded types

When the compiler encounters c.Distance(p)

  1. First try to find func (Cricle) Distance(Point)
  2. If it does not exist, it looks for the method within the embedded fields
  3. If it finds one, it will generate additional wrapper so that it could be called seamlessly.
Method Values and Expressions

Does Go support function overloading?(functions with the same name) discussion

Defining Anonymous functions within a loop discussion

Be careful when defining anonymous functions, which use the iterator variable, within a loop. Consider a situation in which you need to define functions which reference elements of a slice.

names := []string{"cwkim", "sublee", "suminb", "yeonghoey"}

funcs := []func(){}
for _, name := range names {
    funcs = append(funcs, func() {
        fmt.Println(name) // wrong! `name` changes over the for loop
    })
}

for _, f := range funcs {
    f()
}
yeonghoey
yeonghoey
yeonghoey
yeonghoey

To fix this, we need to define a new scope variable and make the function reference it.

names := []string{"cwkim", "sublee", "suminb", "yeonghoey"}

funcs := []func(){}
for _, name := range names {
    name := name // necessary!
    funcs = append(funcs, func() {
        fmt.Println(name)
    })
}

for _, f := range funcs {
    f()
}
sublee
cwkim
suminb
yeonghoey