Golang CSE 4102 Prof Steven A Demurjian Computer

  • Slides: 62
Download presentation
Golang CSE 4102 Prof. Steven A. Demurjian Computer Science & Engineering Department The University

Golang CSE 4102 Prof. Steven A. Demurjian Computer Science & Engineering Department The University of Connecticut 371 Fairfield Way, Box U-255 Storrs, CT 06269 -3255 Steven. Demurjian@uconn. edu http: //www. engr. uconn. edu/~steve (860) 486– 4818 (Office) (860) 486 -3719 (CSE Office) Golang-1

Overview of Presentation m CSE 4102 Found Set of PPTs at: http: //www. getresourceinc.

Overview of Presentation m CSE 4102 Found Set of PPTs at: http: //www. getresourceinc. com/golang/ q Day 2, Day 3, Day 4, Day 5 Golang-2

Golang • Compiled • Flexible, lightweight, compact • Supports GC, concurrency • http: //golang.

Golang • Compiled • Flexible, lightweight, compact • Supports GC, concurrency • http: //golang. org/ • GC/GCCGO • http: //www. getresourceinc. com/golang/

Golang • wget https: //storage. googleapis. com/golang/go 1. 4. 2. linuxamd 64. tar. gz

Golang • wget https: //storage. googleapis. com/golang/go 1. 4. 2. linuxamd 64. tar. gz • tar -C /usr/local -xzf go 1. 4. 2. linux-amd 64. tar. gz • go version • export GOROOT=/usr/local/go • export PATH=$PATH: $GOROOT/bin • export GOPATH=$HOME/go

Golang • go build • • • compiles the packages named by the import

Golang • go build • • • compiles the packages named by the import paths all dependencies are compiled does not install the results go build [-o output] [-i] [build flags] [packages] build is parallellized you can switch go native compiler and linker with gcc compilers • go clean removes your previously built code • go doc • Shows the documentation for a package, symbol or method • go doc json. Number. Int 64 or godoc encoding/json Number

Golang • go run • • go test • • Displays the api documentation

Golang • go run • • go test • • Displays the api documentation go get • • Check code style. go tool api • • Format the code. golint • • Prints the version of Go runtime gofmt • • automates testing the packages named by the import paths go version • • go run [build flags] [-exec xprog] gofiles. . . [arguments. . . ] -exec allows to invoke the compiled program using a specified executor $GOOS and $GOARCH allows to cross compile and run in a different simulator Like go install downloads and installs a package go vet • checks the correctness of the code

Golang Your First “Hello World” program. fmt package – Package fmt implements formatted I/O

Golang Your First “Hello World” program. fmt package – Package fmt implements formatted I/O with functions analogous to C's printf and scanf. The format 'verbs' are derived from C's but are simpler. Println function takes a input and output it to the stdout.

Variable Declarations var <name> <type> Golang var a int var b, c *int //

Variable Declarations var <name> <type> Golang var a int var b, c *int // note difference from C var d []int type S struct { a, b int } Statement separator ‘; ’ implicit

Golang Casting : Unlike in C, in Go assignment between items of different type

Golang Casting : Unlike in C, in Go assignment between items of different type requires an explicit conversion. var i int = 8 var f float 64 f = i //compile error f = float 64(i) // no error

Operators Golang + & += &= && == != ( ) - | -=

Operators Golang + & += &= && == != ( ) - | -= |= || < <= [ ] * ^ *= ^= <- > >= { } / << /= <<= ++ = : = , ; % >> %= >>= -- !. . : &^ &^= Comparator operators >, <, <=, >=, != Logical Operators &&, ||, ! Binary/Bitwise Operators &, |, <<, >> Type initialization operator : = Unary Operators : & ! * + - ^ |

Golang Operators Precedence Operators 5 / % << >> & &^ 4 +-|^ 3

Golang Operators Precedence Operators 5 / % << >> & &^ 4 +-|^ 3 != == < <= > >= 2 && 1 || Unary Operators : & ! * + - ^

Variable Declarations… Golang var ( i int nanoseconds uint 64 = 1 e 9

Variable Declarations… Golang var ( i int nanoseconds uint 64 = 1 e 9 int 1, float 1, string 1 = 1, 2. 0, "hi" ) : = construct a, b, c, d, e : = 1, 2. 0, "three", FOUR, 5 e 0 i //multi-variate assignment

Golang const (Monday, Tuesday = 1 , 2) const ( Monday = iota //

Golang const (Monday, Tuesday = 1 , 2) const ( Monday = iota // 0 Tuesday = iota // 1 ) const ( myname = “srini” )

Golang Keywords The following keywords are reserved and may not be used as identifiers.

Golang Keywords The following keywords are reserved and may not be used as identifiers. break default func interface select case defer go map struct chan else goto package switch const fallthrough if range type continue for import return var

Golang Literals Integers 42 0600 0 x. Bad. Face 170141183460469231731687303715884105727 0. 72. 40 072.

Golang Literals Integers 42 0600 0 x. Bad. Face 170141183460469231731687303715884105727 0. 72. 40 072. 40 // == 72. 40 2. 71828 Real/Float 1. e+0 6. 67428 e-11 1 E 6. 25. 12345 E+5 Imaginary 0 i 011 i // == 11 i 0. i 2. 71828 i 1. e+0 i 6. 67428 e-11 i 1 E 6 i. 25 i. 12345 E+5 i

Golang Literals Rune 'a’ 'ä’ '本’ 't’ '�00’ '�07’ '377' 'x 07’ 'xff’ 'u

Golang Literals Rune 'a’ 'ä’ '本’ 't’ '00’ '07’ '377' 'x 07’ 'xff’ 'u 12 e 4’ 'U 00101234’ Incorrect runes: ''' 'aa' 'xa' '' 'u. DFFF' 'U 00110000’ Strings `abc` // same as "abc" `n n` // same as "\nn\n" """ // same as `"` "Hello, world!n" "日本語" "u 65 e 5本U 00008 a 9 e" "xffu 00 FF"

Golang Arrays & Slices An array is a numbered sequence of elements of a

Golang Arrays & Slices An array is a numbered sequence of elements of a single type, called the element type. The number of elements is called the length and is never negative The elements can be addressed by integer indices 0 through len(a)-1 Each element in the arrays is implicitly zeroed Arrays are values, ex: var a [3]int where a represent the entire array and not a pointer to the beginning of the arrays. Go provides built-in functions : len, cap, copy on arrays. http: //www. getresourceinc. com/golang/

Golang Arrays & Slices var a [0]int //array of length 0, useless var a

Golang Arrays & Slices var a [0]int //array of length 0, useless var a [3]int //array of length 3 var a [3]int = [3]int{1, 2, 3} or a : = [3]int{1, 2, 3} //array of length 3 a = new([]int, 10) //creates an array of 10 ints var a [3]int a = [3]int{1, 2, 3} a = […]int{1, 2, 3} // creates array of length 3

Golang Arrays & Slices Arrays are fixed length, slices are not slice is reference

Golang Arrays & Slices Arrays are fixed length, slices are not slice is reference to a section of array a[1: 3], a[3: ], a[: ] var a []int a = []int{1, 2, 3} // slice is of length 3 var a [10]int = []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 0} b = a[3] => {4} b = a[3: 3] => {} b = a[3: 5] => {4, 5} b = a[3: ] => {4, 5, 6, 7, 8, 9, 0} b = a[: 3] => {1, 2, 3}

Golang Arrays & Slices Append – builtin function to append element to an array

Golang Arrays & Slices Append – builtin function to append element to an array a : = []int{1, 2} //a has two elements 1, 2 a = append(a, 3) //a has three elements 1, 2, 3 s = make([]int, 3, 5) // creates a array of length 3 {0, 0, 0} s = append(s, 4) // adds a new element 4 {0, 0, 0, 4} s = append(s, 5) // adds a new element 4 {0, 0, 0, 4} s = append(s, 6) // adds a new element 4 {0, 0, 0, 4, 5} and capacity increased from 5 to a larger number. Copy s : = {1, 2, 3} var b [5]int copy (s, b) //copy only copies if b has space

Golang Maps A map is a key-value pair Key and Value are two different

Golang Maps A map is a key-value pair Key and Value are two different valid go types Size of map is not fixed like an array Map is like slice, it is a reference type. var m map[string]float 64 m = map[string]float 64{"1": 1, "pi": 3. 1415} m = make(map[string]float 64)

Golang Maps Assigning key-value pair m[“ 1”] = 2 a : = m[“ 1”]

Golang Maps Assigning key-value pair m[“ 1”] = 2 a : = m[“ 1”] Delete an entry from the map with specified key. delete(m, “ 1”) // deletes and entry builtins useful are len, copy, make

Golang Maps Check existense of a key in the map value, ok : =

Golang Maps Check existense of a key in the map value, ok : = m[x] Is ok true/false?

Golang Maps Exercise: Create a map with the following association Player from a base

Golang Maps Exercise: Create a map with the following association Player from a base ball team A Number of points in the season Joe 22 Alex 48 Gary 12 Frank 32 Print the map. Mike 24 Write code to see if Player Mike exists delete player Mike as he left the team A check to see if Mike is still associated to team A

Docker Dojo - golang Complex Arrays and Maps Two Dimensional Arrays can describe associations

Docker Dojo - golang Complex Arrays and Maps Two Dimensional Arrays can describe associations var a [][]string Maps can be a map of var a map[string]int Map can also have another complex data structure as value var a map[string][]int …

Golang Structures Struct in Go represents an object. But unlike any object oriented language,

Golang Structures Struct in Go represents an object. But unlike any object oriented language, structs in Go do not compose methods Contains named fields Structs can have associated methods type point struct { x, y float 64 } Structs are values Structs and their fields can be exported type Point struct { x, Y float 64 }

Golang Struct initialization Type Point struct { x, y float 64 } var p

Golang Struct initialization Type Point struct { x, y float 64 } var p Point p = Point{} p = Point{2. 2, 3. 3} p = Point{y: 3. 3} pp = new (Point) (*pp). x = 1. 1, pp. y = 2. 2 Structures

Golang Structures Exercise create a structure rectangle with length and width create a structure

Golang Structures Exercise create a structure rectangle with length and width create a structure for circle with radius and origin create a sample instance of both and print their description. ex: myrectangle has following dimensions, length = 2. 0 abd width = 3. 0 mycircle has origin at (1, 3. 2) and a radius of 3. 15

Golang Anonymous fields: type another. Struct { x, y int } type point struct

Golang Anonymous fields: type another. Struct { x, y int } type point struct { another. Struct x, y float 64 } p : = point { {1, 2}, 1. 0, 2. 0} fmt. Println(p. another. Struct) Structures

Golang Control Statements if if x < 0 { … } else { …

Golang Control Statements if if x < 0 { … } else { … } if v, err: =eval(me); v > 0 && err != nil { … } http: //www. getresourceinc. com/golang/

Golang Control Statements if var x bool false if x { … } var

Golang Control Statements if var x bool false if x { … } var s string = ”efg” if s > ”abc” //true If s >= ”fgh” //false

Golang Control Statements if Exercise Create variables to hold todays temperature and age write

Golang Control Statements if Exercise Create variables to hold todays temperature and age write code to print one of the following if age is below 10 and temperature is below 48. 4, “Hot chocolate is served” if age is 18+ and less than 60 and temperature is below 48. 4, “Coffee is server” for all others “Hot soup is served” Test your logic for all possible combinations

Golang Control Statements for i: =0; i<10; i++ { … } for ; ;

Golang Control Statements for i: =0; i<10; i++ { … } for ; ; { // or for { … break; } break lets you exit a for loop continue starts the next iteration of the for loop from the top

Golang Control Statements for Exercise Write a for loop to print first 10 positive

Golang Control Statements for Exercise Write a for loop to print first 10 positive number or first 10 even positive numbers or first 10 prime numbers

Golang Control Statements for key, value : = range map { … } for

Golang Control Statements for key, value : = range map { … } for index, value : = range array { … } for inder. Or. Key : = range X { … } //you can drop value in a map or just iterate a string

Golang Control Statements for Exercise create a table of player vs points from the

Golang Control Statements for Exercise create a table of player vs points from the map exercise using for loop with range print… Player Player Joe scored 22 points Alex scored 48 points Gary scored 12 points Frank scored 32 points Mike scored 24 points

Golang Control Statements switch Switch allows to run a specified block of statements based

Golang Control Statements switch Switch allows to run a specified block of statements based on a value Golang switch does not need a explicit break var a int = 8 switch a%5 { case 0 : fmt. Println( “a 5 multiple”) case 4 : fmt. Println( “top”) case 1 : fmt. Println( “bottom”) default : fmt. Println( “somewhere”) }

Golang Control Statements switch Switch work on character and strings switch c { case

Golang Control Statements switch Switch work on character and strings switch c { case '&': esc = "& " case ''': esc = "&apos; " case '<': esc = "< " case '>': esc = "> " case '"': esc = "" " default: panic("unrecognized escape character") }

Golang Control Statements switch Fallthrough allows switch to execute the next statement var a

Golang Control Statements switch Fallthrough allows switch to execute the next statement var a int = 8 switch a%5 { case 0 : fmt. Println( “a 5 multiple”) case 4 : fmt. Println( “top”) fallthrough case 1 : fmt. Println( “bottom”) default : fmt. Println( “somewhere”) }

Golang Control Statements switch Special use of switch to detect type var a int

Golang Control Statements switch Special use of switch to detect type var a int = 8 Switch a. (type) { case float 64 : fmt. Println( “float”) case int : fmt. Println( “integer”) case char : fmt. Println( “char”) default : fmt. Println( “unknown”) }

Builtin functions • new • make • len • append • panic len(“abc”) a

Builtin functions • new • make • len • append • panic len(“abc”) a : = []string{"a", "b"} a = append(a, "c") fmt. Println(len(a), a) Golang

Stop here • Remainder are functions, etc.

Stop here • Remainder are functions, etc.

Golang Functions allow modularization func My. Sqrt(f float 64) (v float 64, ok bool)

Golang Functions allow modularization func My. Sqrt(f float 64) (v float 64, ok bool) { if f >= 0 { v, ok = math. Sqrt(f), true } return v, ok //or simply return } value, ok : = My. Sqrt(50. 0) or Value, _ : = My. Sqrt(50. 0) http: //www. getresourceinc. com/golang/

Golang Functions cannot access variable in the calling function func f() { fmt. Println(x)

Golang 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)

Golang Function are executed on stack func f 2() { fmt. Println("in f 2")

Golang Function are executed on stack func f 2() { fmt. Println("in f 2") } func f 1() { fmt. Println("in f 1") f 2() } func main() { b() }

Golang Functions can return multiple values package main func sqrt(x float 64) (float 64,

Golang Functions can return multiple values package main func sqrt(x float 64) (float 64, error) { … } func main() { var x float 64 = 5. 76 square_root, err : = sqrt(x) if err == nil { …. } }

Golang defer statement : runs before the function returns, helps cleanup package main import

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() }

Golang Function Literals are Closure Create a func inside a function It has access

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()) }

Function Literals are Closure func adder() func(int) int { var x int return func(delta

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)) } Golang

No inner functions Golang Pass by value vs reference Variadic Functions • func add(args.

No inner functions Golang Pass by value vs reference Variadic Functions • func add(args. . . int) int => add(1, 3, 5, 7)

Golang By using. . . before the type name of the last parameter you

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)) }

Golang Recursion happen when a function calls itself Closure and Recursion are two power

Golang 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

Golang Panic and Recover panic is a built-in function which causes a run time

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) }

Golang Pass by Value vs Reference func square_values(x float 64) { return x *

Golang Pass by Value vs Reference func square_values(x float 64) { return x * x } func square(x *float 64) { *x = *x * *x } func main() { x : = 1. 5 square(&x) }

Golang type point struct { Methods on Structures x, y float 64 } //

Golang type point struct { Methods on Structures x, y float 64 } // A method on Point, passing point p in value func (p point) Dist(point p 1) float 64 { return math. Sqrt(math. Sqr(p. x-p 1. x) + math. Sqr(p. y-p 1. y)) } or better func (p *Point 3) Dist(point p 1) float 64 { return math. Sqrt(math. Pow(p. x-p 1. x, 2) + math. Pow(p. y-p 1. y, 2)) } p, p 1 : = point{0, 0}, point{3, 4} p. Dist(p 1) //should return 5

Golang Methods on Anonymous Structures Anonymous embedding allows to call methods directly on that

Golang Methods on Anonymous Structures Anonymous embedding allows to call methods directly on that struct. type point struct { x, y float 64 } func (p *Point 3) Dist(point p 1) float 64 { return math. Sqrt(math. Pow(p. x-p 1. x, 2) + math. Pow(p. y-p 1. y, 2)) } type circle struct { point radius float 64 } circle c 1 = circle{point{0, 0}, 4}, c 2 = circle{point{2, 3}, 4} Distance between circles => c 1. dist(c 2. point)

Golang Methods are attached to a named type, say Foo and are statically bound

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 Day int func (day Day) String() string { … }

Golang Scoping 1) Go has package scope (C++ has file scope). 2)�� Spelling determines

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".

Golang Scoping 1) Go has package scope (C++ has file scope). 2)�� Spelling determines

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".

Golang Interfaces define sets of methods. They are pure and abstract: no implementation, no

Golang 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{}.

Golang Sort Interface Has three methods type Interface interface { // Len is the

Golang Sort Interface Has three methods type Interface interface { // Len is the number of elements in the collection. Len() int // Less reports whether the element with // index i should sort before the element with index j. Less(i, j int) bool // Swap swaps the elements with indexes i and j. Swap(i, j int) }

Golang Sort Interface Exercise : Write a function that sorts the table container player,

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.