0% found this document useful (0 votes)
14 views

ACP Lecture 03 - Functions

Uploaded by

Mujtaba
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

ACP Lecture 03 - Functions

Uploaded by

Mujtaba
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 18

Advance Computer Programming – GO

Lecture – 03
GO language Functions

Instructor: Syed Mujtaba Hassan


Email: [email protected]
Session: Fall 2022
Riphah School of Computing and Innovation (RSCI)
Riphah International University, Lahore
Introduction to Functions- GO Language
In Golang, we declare a function using the func keyword. A function has a name, a
list of comma-separated input parameters along with their types, the result type(s),
and a body.
Following is an example of a simple function called avg that takes two input
parameters of type float64 and returns the average of the inputs. The result is also
of type float64.
package main
import "fmt"
func avg(x float64, y float64) float64 {
return (x + y) / 2
}
func main() {
x := 5.75
y := 6.25
Continue…

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

Go functions are capable of returning multiple values. That’s right! This is


something that most programming languages don’t support natively. But Go is
different.
func getStockPriceChange(prevPrice, currentPrice float64) (float64, float64) {
change := currentPrice - prevPrice
percentChange := (change / prevPrice) * 100
return change, percentChange
}
Defer- GO Language

Go has many of the common control-flow keywords found in other programming


languages such as if, switch, for, etc. One keyword that isn’t found in most other
programming languages is defer, and though it’s less common you’ll quickly see
how useful it can be in your programs.
One of the primary uses of a defer statement is for cleaning up resources, such as
open files, network connections, and database handles. When your program is
finished with these resources, it’s important to close them to avoid exhausting the
program’s limits and to allow other programs access to those resources. defer
makes our code cleaner and less error prone by keeping the calls to close the
file/resource in proximity to the open call.
In this article we will learn how to properly use the defer statement for cleaning up
resources as well as several common mistakes that are made when using defer.
Continue…

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 used to cleanup resources.

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…

 This has various advantages:


• It keeps our Close call near our Open call so it's easier to understand.
• If our function had multiple return statements (perhaps one in an if and one in an
else), Close will happen before both of them.
• Deferred Functions are run even if a runtime panic occurs.
• Deferred functions are executed in LIFO order, so the above code prints: 4 3 2 1
0.
• You can put multiple functions on the "deferred list", like this example.
Built in functions – Go Language
There are many built-in functions in go, which can be used directly without
introducing related packages. In the go source code builtin package builtin.go All
built-in functions of go are defined in the file. However, the file only defines and
describes all built-in functions, and does not contain any implementation code of
functions. Besides defining built-in functions, the file also defines some built-in
types.
len(“123”)
println(“log”)
fmt.Println ("FMT") // used by non built-in functions to call functions in the FMT
package

Common built-in functions


close : It is used for the sender to close Chan. It is only applicable to two-way or
sending channels.
len 、 cap : It is used to obtain the length or quantity of array, slice, map, string,
Chan type data, len returns length and cap returns capacity;
new 、 make : New is used for memory allocation of value type and user-defined
type; new (T) allocates zero value of type T and returns its pointer to type T; make
is used for memory allocation of reference type (slice, map, Chan) and returns
initialized value, and the usage of different types is different.
Continue…

Make (Chan int) creates a buffer free channel


Make (Chan int, 10) creates a channel with buffer 10
Make ([] int, 1,5) creates a slice with a length of 1 and a capacity of 5
Make ([] int, 5) creates slices with capacity length of 5
Make (map [int] int) creates a map with no specified capacity
Make (map [int] int, 2) create a map with a capacity of 2
Function closures – Go Language
Go functions may be closures. A closure is a function value that references
variables from outside its body. The function may access and assign to the
referenced variables; in this sense the function is "bound" to the variables.

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

Recursion is a process in which a function calls itself implicitly or explicitly and


the corresponding function is called recursive function. Go language supports
special feature called anonymous function. It is a function that doesn’t contain any
name. It is used to create an inline function. Recursive functions can be declared &
defined as anonymous also. A recursive anonymous function is also known
as recursive function literal.
Continue…
// Golang program to show
// how to create an recursive
// Anonymous function
package main
import "fmt"
func main() {
// Anonymous function
var recursiveAnonymous func()
recursiveAnonymous = func() {
// Printing message to show the
// function call and iteration.
Continue…

fmt.Println("Anonymous functions could be recursive.")


// Calling same function
// recursively
recursiveAnonymous()
}
// Main calling of
// the function
recursiveAnonymous()
}
Useful Ways to Use Closures in Go

• Isolating data
• Wrapping functions and creating middleware
• Deferring work
• Accessing data that typically isn’t available
• Binary searching with the sort package

You might also like