38. Go - Functions

Function format:

func (receiver) identifier(arguments) (returns) {CODE}

// can receive more than one argument by using variadic parameter (...), also applies to returns


Example:

// pointer used on personB to change the todd variable's values in main func.

package main

import "fmt"

type personB struct {
    name string
    age  int
}

func (p *personB) rename(n string) string {
    p.name = n
    return p.name
}

func main() {
    todd := personB{
        name: "todd",
        age:  10,
    }
    fmt.Println(todd.name)
    fmt.Println(todd.rename("bobby"))
    fmt.Println(todd.name)
}


Anonymous Functions:

// Format: func(parameters) {CODE} (parameters input)

// Use inside functions. Code will autorun

    func(x int) {
        fmt.Println(x)
    }(50)


Func Expressions (variables as a func):

package main

import "fmt"

func main() {

    test := func() {
        fmt.Println("HETS")
    }
    test()
}


Returning a Func from a Func:

func returnFunc() func() int {
    return func() int {
        return 5
    }
}

Extreme Example:

package main

import "fmt"

func main() {
    fmt.Println(returnFuncs()()()()())
}

func returnFuncs() func() func() func() func() int {
    return func() func() func() func() int {
        return func() func() func() int {
            return func() func() int {
                return func() int {
                    return 666
                }
            }
        }
    }
}


Return Function with inner closure scope:

package main

import "fmt"

func printerr() func() int {
    x := 0

    return func() int {
        x++
        return x
    }
}

func main() {
    test1 := printerr()
    fmt.Println(test1())
    test2 := printerr()
    fmt.Println(test2())

    fmt.Println("TWO")
    fmt.Println(test2())
    fmt.Println(test2())
    fmt.Println(test2())
    fmt.Println(test2())

    fmt.Println("ONE")
    fmt.Println(test1())

}

// test1 is a printerr function with its own scope of x variable.

// test2 cannot access test1's variable x


Comments

Popular posts from this blog

2. FreeCodeCamp - Dynamic Programming - Learn to Solve Algorithmic Problems & Coding Challenges

20. Data Analytics - Analyze Data to Answer Questions - Week 1

3. Algorithms - Selection Sort