ACP Lecture 03 - Functions
ACP Lecture 03 - Functions
Lecture – 03
GO language Functions
result := avg(x, y)
fmt.Printf("Average of %.2f and %.2f = %.2f\n", x, y, result)
}
The input parameters and return type(s) are optional for a function. A function can
be declared without any input and output.
Function parameters and return. type(s) are optional
Functions with multiple return values
A defer statement adds the function call following the defer keyword onto a stack.
All of the calls on that stack are called when the function in which they were added
returns. Because the calls are placed on a stack, they are called in last-in-first-out
order.
package main
import "fmt"
func main() {
defer fmt.Println("Bye")
fmt.Println("Hi")
}
Continue…
Multiple defer Statements.
package main
import "fmt"
func main() {
defer fmt.Println("one")
defer fmt.Println("two")
defer fmt.Println("three")
}
defer file.Close()
_, err = io.WriteString(file, text)
if err != nil {
return err
}
Deferred Functions Calls
Go has a special statement called defer that schedules a function call to be run after
the function completes. Consider the following example:
package main
import "fmt"
func first() {
fmt.Println("Print First")
}
func second() {
fmt.Println("Print Second")
}
func main() {
defer second()
first()
}
With defer
func ReadWrite() bool {
file.Open("file")
defer file.Close() //file.Close() is added to defer list
// Do your thing
if failureX {
return false // Close() is now done automatically
}
if failureY {
return false // And here too
}
return true // And here
}
Continue…
For example, the adder function returns a closure. Each closure is bound to its own
sum variable.
package main
import "fmt"
func adder() func(int) int {
sum := 0
return func(x int) int {
sum += x
return sum
}
}
Continue…
func main() {
pos, neg := adder(), adder()
for i := 0; i < 10; i++ {
fmt.Println(
pos(i),
neg(-2*i),
)
}
}
Recursive Anonymous Function in Golang
• Isolating data
• Wrapping functions and creating middleware
• Deferring work
• Accessing data that typically isn’t available
• Binary searching with the sort package