Download presentation
Presentation is loading. Please wait.
Published byGarey Greer Modified over 8 years ago
1
Golang Functions Functions allow modularization func MySqrt(f float64) (v float64, ok bool) { if f >= 0 { v,ok = math.Sqrt(f), true } return v, ok //or simply return } value, ok := MySqrt(50.0) or Value, _ := MySqrt(50.0)
2
Golang Functions Functions cannot access variable in the calling function func f() { fmt.Println(x) } func main() { x := 5 f() } Either declare a global ‘x’ or pass it to the function f(x)
3
Golang Function are executed on stack func f2() { fmt.Println("in f2") } func f1() { fmt.Println("in f1") f2() } func main() { b() }
4
Golang Functions can return multiple values package main func sqrt(x float64) (float64,error) { … } func main() { var x float64 = 5.76 square_root, err := sqrt(x) if err == nil { …. }
5
Golang defer statement : runs before the function returns, helps cleanup package main import "fmt” func trace(s string) { fmt.Println("entering:", s) } func untrace(s string) { fmt.Println("leaving:", s) } func a() { trace("a") defer untrace("a") fmt.Println("in a") } func b() { trace("b") defer untrace("b") fmt.Println("in b") a() } func main() { b() }
6
Golang Function Literals are Closure Create a func inside a function It has access to the local variables in that scope func main() { x := 0 f := func() int { x += 2 } fmt.Println(f()) }
7
Golang Function Literals are Closure func adder() func(int) int { var x int return func(delta int) int { x += delta return x } func main() { f := adder() fmt.Println(f(1)) fmt.Println(f(20)) fmt.Println(f(300)) }
8
Golang No inner functions Pass by value vs reference Variadic Functions func add(args...int) int => add(1,3,5,7)
9
Golang By using... before the type name of the last parameter you can indicate that it takes zero or more of those parameters. func add(args...int) int { total := 0 for _, v := range args { total += v } return total } func main() { fmt.Println(add(1,2,3)) }
10
Golang Recursion Recursion happen when a function calls itself Closure and Recursion are two power prnciples of functional programming. func factorial(x uint) uint { if x == 0 { return 1 } return x * factorial(x-1) } factorial(3) => 3 * factorial(2) => 3 * 2 * factorial(1) => 3 * 2 * 1 * factorial(0) => 3 * 2 * 1 * 1
11
Golang Panic and Recover panic is a built-in function which causes a run time error panic() stops the execution of the function and returns (unwinds the stack) It unwinds the stack until a recover() function handles the panic func main() { panic("PANIC") str := recover() fmt.Println(str) }
12
Golang Pass by Value vs Reference func square_values(x float64) { return x * x } func square(x *float64) { *x = *x * *x } func main() { x := 1.5 square(&x) }
13
Golang Exercise Write a function which takes an integer and halves it and returns true if it was even or false if it was odd. For example half(1) should return (0, false) and half(2) should return (1, true) Write a function with one variadic parameter that finds the greatest number in a list of numbers. Homework The Fibonacci sequence is defined as: fib(0) = 0, fib(1) = 1, fib(n) = fib(n-1) + fib(n-2). Write a recursive function which can find fib(n)
14
Golang Methods on Structures type point struct { x, y float64 } // A method on Point, passing point p in value func (p point) Dist(point p1) float64 { return math.Sqrt(math.Sqr(p.x-p1.x) + math.Sqr(p.y-p1.y)) } or better func (p *Point3) Dist(point p1) float64 { return math.Sqrt(math.Pow(p.x-p1.x,2) + math.Pow(p.y-p1.y,2)) } p,p1 := point{0,0}, point{3,4} p.Dist(p1) //should return 5
15
Golang Methods on Anonymous Structures Anonymous embedding allows to call methods directly on that struct. type point struct { x, y float64 } func (p *Point3) Dist(point p1) float64 { return math.Sqrt(math.Pow(p.x-p1.x,2) + math.Pow(p.y-p1.y,2)) } type circle struct { point radius float64 } circle c1 = circle{point{0,0},4}, c2 = circle{point{2,3},4} Distance between circles => c1.dist(c2.point)
16
Golang Methods are attached to a named type, say Foo and are statically bound Go automatically indirects/dereferences values for you when invoking methods. Methods are not just for structs. They can be defined for any (non- pointer) type. type Day int func (day Day) String() string { … }
17
Golang Scoping 1)Go has package scope (C++ has file scope). 2) Spelling determines exported/local (pub/priv). 3) Structs in the same package have full access to one another's fields and methods. 4) Local type can export its fields and methods. 5) No true subclassing, so no notion of "protected".
18
Golang Scoping 1)Go has package scope (C++ has file scope). 2) Spelling determines exported/local (pub/priv). 3) Structs in the same package have full access to one another's fields and methods. 4) Local type can export its fields and methods. 5) No true subclassing, so no notion of "protected".
19
Golang Interfaces Interfaces define sets of methods. They are pure and abstract: no implementation, no data fields. Go has a clear separation between interface and implementation. Interface values are just that: values. They contain any concrete value that implements all the methods defined in the interface. Types implement interfaces just by having methods. They do not have to declare that they do so. For instance, every type implements the empty interface, interface{}.
20
Golang Sort Interface Has three methods type Interface interface { // Len is the number of elements in the collection. Len() intint // Less reports whether the element with // index i should sort before the element with index j. Less(i, j int) boolint) bool // Swap swaps the elements with indexes i and j. Swap(i, j int)int) }
21
Golang Sort Interface Exercise : Write a function that sorts the table container player, points scored in the alphabetical order Homework : Create a employee structure with name, age and salary. Implement sort interface on the employee display employee records alphabetically by name or numerically in ascending order on salary.
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.