Download presentation
1
History of Computing – Golang
Prof. Steven A. Demurjian Computer Science & Engineering Department The University of Connecticut 371 Fairfield Way, Box U-255 Storrs, CT (860) 486–4818 (Office) (860) (CSE Office)
2
Overview of Presentation
Found Set of PPTs at: Day 2, Day 3, Day 4, Day 5
3
Golang Compiled Flexible, lightweight, compact
Supports GC, concurrency GC/GCCGO
4
Golang wget amd64.tar.gz tar -C /usr/local -xzf go1.4.2.linux-amd64.tar.gz go version export GOROOT=/usr/local/go export PATH=$PATH:$GOROOT/bin export GOPATH=$HOME/go
5
Golang go build go clean go doc
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 go clean removes your previously built code go doc Shows the documentation for a package, symbol or method go doc json.Number.Int64 or godoc encoding/json Int64 or godoc encoding/json Number
6
Golang go run go test go version gofmt golint go tool api go get
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 go test automates testing the packages named by the import paths go version Prints the version of Go runtime gofmt Format the code. golint Check code style. go tool api Displays the api documentation go get Like go install downloads and installs a package go vet checks the correctness of the code
7
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.
8
Golang Variable Declarations var <name> <type> var a int
var b, c *int // note difference from C var d []int type S struct { a, b int } Statement separator ‘;’ implicit
9
Golang Casting : Unlike in C, in Go assignment between items of different type requires an explicit conversion. var i int = 8 var f float64 f = i //compile error f = float64(i) // no error
10
Golang Operators + & += &= && == != ( ) - | -= |= || < <= [ ]
+ & += &= && == != ( ) - | -= |= || < <= [ ] * ^ *= ^= <- > >= { } / << /= <<= = := , ; % >> %= >>= ! : &^ &^= Comparator operators >, <, <=, >=, != Logical Operators &&, ||, ! Binary/Bitwise Operators &, |, <<, >> Type initialization operator := Unary Operators : & ! * + - ^ |
11
Operators Unary Operators : & ! * + - ^
Golang Operators Unary Operators : & ! * + - ^ Precedence Operators 5 / % << >> & &^ 4 + - | ^ 3 != == < <= > >= 2 && 1 ||
12
Golang var ( i int nanoseconds uint64 = 1e9
Variable Declarations… var ( i int nanoseconds uint64 = 1e9 int1, float1, string1 = 1, 2.0, "hi" ) := construct a, b, c, d, e := 1, 2.0, "three", FOUR, 5e0i //multi-variate assignment
13
Golang const (Monday, Tuesday = 1 ,2) const ( Monday = iota // 0
Tuesday = iota // 1 ) myname = “srini”
14
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
15
Golang Literals Integers
0600 0xBadFace // == Real/Float 1.e e-11 1E E+5 Imaginary 0i 011i // == 11i 0.i i 1.e+0i e-11i 1E6i .25i E+5i
16
Golang Literals Rune 'a’ 'ä’ '本’ '\t’ '\000’ '\007’ '\377'
'\x07’ '\xff’ '\u12e4’ '\U ’ Incorrect runes: '\'' 'aa' '\xa' '\0' '\uDFFF' '\U ’ Strings `abc` // same as "abc" `\n \n` // same as "\\n\n\\n" "\n" "\"" // same as `"` "Hello, world!\n" "日本語" "\u65e5本\U00008a9e" "\xff\u00FF"
17
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.
18
Golang Arrays & Slices var a [0]int //array of length 0, useless
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
19
Golang Arrays & Slices Arrays are fixed length, slices are not slice is reference to a section of array a[1:3], a[: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}
20
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
21
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]float64 m = map[string]float64{"1":1, "pi":3.1415} m = make(map[string]float64)
22
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
23
Golang Maps Check existense of a key in the map value, ok := m[x]
Is ok true/false?
24
Golang Maps Exercise: Create a map with the following association
Print the map. 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 Player from a base ball team A Number of points in the season Joe 22 Alex 48 Gary 12 Frank 32 Mike 24
25
Complex Arrays and Maps
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]map[string]int Map can also have another complex data structure as value var a map[string][]int …
26
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 float64 } Structs are values Structs and their fields can be exported type Point struct { x, Y float64
27
Golang Structures Struct initialization Type Point struct {
x, y float64 } 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
28
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
29
Golang Structures Anonymous fields: type anotherStruct { x,y int }
type point struct { anotherStruct x, y float64 p := point { {1,2}, 1.0, 2.0} fmt.Println(p.anotherStruct)
30
Golang Control Statements if if x < 0 { … } else { }
if v,err:=eval(me);v > 0 && err != nil {
31
Golang Control Statements if var x bool false if x { … }
var s string = ”efg” if s > ”abc” //true If s >= ”fgh” //false
32
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
33
Control Statements for
Golang Control Statements for 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
34
Control Statements for
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
35
Control Statements for
Golang Control Statements for for key,value := range map { … } for index,value := range array { for inderOrKey := range X { … } //you can drop value in a map or just iterate a string
36
Control Statements for
Golang Control Statements for Exercise create a table of player vs points from the map exercise using for loop with range print… Player Joe scored 22 points Player Alex scored 48 points Player Gary scored 12 points Player Frank scored 32 points Player Mike scored 24 points
37
Control Statements switch
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”) }
38
Control Statements switch
Golang Control Statements switch Switch work on character and strings switch c { case '&': esc = "&" case '\'': esc = "'" case '<': esc = "<" case '>': esc = ">" case '"': esc = """ default: panic("unrecognized escape character") }
39
Control Statements switch
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”) }
40
Control Statements switch
Golang Control Statements switch Special use of switch to detect type var a int = 8 Switch a.(type) { case float64 : fmt.Println( “float”) case int : fmt.Println( “integer”) case char : fmt.Println( “char”) default : fmt.Println( “unknown”) }
41
Golang Builtin functions new make len append panic len(“abc”)
a := []string{"a","b"} a = append(a,"c") fmt.Println(len(a),a)
42
Stop here Remainder are functions, etc.
43
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)
44
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)
45
Golang Function are executed on stack func f2() { fmt.Println("in f2")
} func f1() { fmt.Println("in f1") f2() func main() { b() }
46
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 { ….
47
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() }
48
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())
49
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))
50
Golang No inner functions Pass by value vs reference
Variadic Functions func add(args ...int) int => add(1,3,5,7)
51
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))
52
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
53
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) }
54
Pass by Value vs Reference
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)
55
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
56
Methods on Anonymous Structures
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)
57
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 { … }
58
Golang Go has package scope (C++ has file scope).
Scoping 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".
59
Golang Go has package scope (C++ has file scope).
Scoping 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".
60
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{}.
61
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) }
62
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.