Download presentation
Presentation is loading. Please wait.
1
CS 370 – Summer 2019 Introduction to Go Programming Language Presenting by Group 1
2
Presentation Overview GO KEY TOPICS What is Go programming language? History of Go Why go is born? Designer team and users Some outstanding features Some basic syntax May be demo here GO programming language
3
What is GO programming language? 03 open source concurrent garbage-collected efficient Go, also known as Golang,is a statically typed, compiled programming language designed at Google. Go is a procedural programming language. scalable simple fun boring (to some)
4
A young programming language HISTORY OF GOLANG LATE 2007: BORN It was developed in 2007 by Robert Griesemer, Rob Pike, and Ken Thompson at Google 2009:OPEN SOURCE It became open source in November 2009 TODAY:MORE POPULAR More and more developers use it Today's version is 1.12.9
5
Design team Robert Griesemer V8 JavaScript engine, Java HotSpot VM Fathers Of GOLANG Rob Pike UNIX, Plan 9, UTF-8 Ken Thompson UNIX, Plan 9, B language, UTF-8
6
Why GO? C++ for servers, plus lots of Java and Python Thousand of engineers Gazillions of lines of code Distributed build system Zillions of machines, which are treated as a modest number of compute clusters GO programming language Go is an answer to problems of scale at Google
7
GO’s Goals GO Go was designed by and for people who write – and read and debug and maintain – large software systems. GO programming language 1 2 3 Go’s purpose is not research programming language design. Go’s purpose is to make its designers’ programming lives better.
8
Who is the User? Google Youtube Docker SoundCloud
9
Advantages of GOLANG GO grows faster than any other language. 1 5 2 3 4 GO compiled into many platforms. GO uses multiple cores. GO has Concurrency and Goroutines. Easy to maintain.
10
Polularity and potential future 03 In early 2017, according to Zdnet's statistics, GO surpassed its competitors, the popularity was 2.6%, climbing from the 54th position in 2016 to the 13th position. GO is the only language with such rapid growth. GO grows faster than any other language
11
Fast build and multiple flatforms 03 The Go programming language is also compiled like Java, but unlike Java, it requires Java Virtual Machine to execute because Java compiles into Byte code, Go compiles to Machine code so it can run immediately with the operating system. It compiles without any further installation. That means, from my computer, I can compile programs running on Mac, Window, Linux. GO compiled into many platforms
12
Multiple cores and easily to scale up 03 In the 1990s, one of the major changes in computer hardware was the addition of cores. Quad-core and octa-core CPUs significantly improve performance. However, programming languages created before that time only run on single-core computers, and they are built not intended to run on multi- core. But Go is different, the late born has created an advantage for it, computer hardware can expand the core, making Go a language that can be more easily scaled. GO uses multiple cores
13
Frendly with HEAP and memory 03 Concurrency is a key feature of the Go programming language to utilize CPU processing power. Usually other programming languages must depend on the allocation of operating system resources to run Concurrency, while Go can run Concurrency without operating system dependency. Concurrency is similar to thread, in Go, communication between goroutine is quite simple with channel, can transmit data between goroutine together by any kind of data. GO has Concurrency and Goroutines Heap
14
JAVA If a Java Thread is created, it uses approximately 1MB of Heap memory, if you create 1000 Thread like that, they will create a heap pressure that will cause the system to be turned off because of a memory shortage. On the other hand, it is difficult to communicate between two or more Thread. GOLANG But with GO is different, when using multi-core processors is feasible, Goroutines can completely replace Thread. Each goroutines only uses 2KB of memory from the heap, so you can create millions of goroutines at any time. More about Goroutine
15
Goroutine Code Example package main import "fmt" func f(from string) { for i := 0; i < 3; i++ { fmt.Println(from, ":", i) } func main() { f("direct") // Using go f() to execute function f() in goroutines. go f("goroutine") go func(msg string) { fmt.Println(msg) }("going") fmt.Scanln() fmt.Println("done") } // Output direct : 0 direct : 1 direct : 2 goroutine : 0 going goroutine : 1 goroutine : 2 Done
16
Advantages of Goroutine Goroutines use memory flexibly for segmented stack, which will increase memory when needed. The boot time of Goroutines is faster than Thread. Communicate between Goroutines using channel is extremely safe. Goroutines and OS threads do not exist 1: 1. Each Gorountine can run multiple threads at the same time, they can be combined into OS threads. GO programming language
17
Maximize simplification 03 GO's syntax is extremely simple, without too complicated syntax like other languages. Go developers come from Google, a large-scale code- base place, and thousands of developers work together, so source code must be simple for any developer to understand and each block of code will minimize side effects. That makes the code easily to be maintained an changed. Easy to maintain
18
Why we can say GO is Special? Go ignores many features of OOP (Object-oriented programming) No Class. Everything is bundled into packages. Go only have structs. No inheritance support. No constructor, annotation, generics or exceptions. That makes Go different from the rest. Looking at the positive side, it makes the code more concise and easier to understand. GO programming language
19
Things that are supported by GO Some old things, some new things
20
Overvie w - All programs written from Go are created by main packages and packages used to run is main - To use other packages, we have to import, for example if we want to print a text to the console, we must use the fmt package Code Packages package main import "fmt" func main() { fmt.Println("Hello World") } GO programming language
21
Code Over view - Go's syntax is similar to C but there are many other points, for example, there is no semicolon at the end of the statement or the data type declared after the variable name - When performing calculations between variables with different data types, we need type conversion: Formula T (v) where T is the data type and v is the value -Constant declaration is similar to declaring a variable but using const and not using the abbreviated syntax “:=“ Variables var message string var c, python, java bool var i, j int = 1, 2 k := 3 i := 55 // int j := 67.8 // float 64 sum := i + int(j) // type conversion fmt.Println(sum) // output: 122 const Pi = 3.14 GO programming language
22
Overvie w - Declare the function using the keyword func, notice that the input parameter also declares the data type after the parameter name - A special feature in GO is that the function can return many results Code Functions func add(x int, y int) int { return x + y } // funtion that return 2 values func swap(x, y string) (string, string) { return y, x } GO programming language
23
Code Over view - In GO, only 1 type of loop is used: for loop. Usage is similar to other languages but the declaration of variables, repeating conditions,... does not need to be enclosed in round brackets - for loop only using a repeating condition, it acts like a while in other languages Loop sum := 0 for i := 0; i < 10; i++ { sum += i } fmt.Println(sum) sum := 0 for sum < 10 { sum += sum } fmt.Println(sum) GO programming language
24
Overvie w - Conditional statement in GO use if, else, switch, and like for loop we also do not need round brackets - With the if statement, we can declare the variable in the conditional statement, and this variable will only work in the block of the if or else statement Code if and else import ( "fmt" "math" ) func pow(x, n, limit float64) float64 { if v := math.Pow(x, n); v < limit { return v } else { fmt.Printf("%g >= %g\n", v, limit) } return limmit } GO programming language
25
Code Over view - The expression in the switch cannot use a constant. There is no need for break commands in each case. Therefore only the first satisfied case is run (from top to bottom) - You can use multiple conditions in a case, or use the keyword fallthrough to allow the next command continue Switch case switch num := 10; { case num < 50: fmt.Printf("%d < 50\n", num) // print: 10 < 50 case num < 100: fmt.Printf("%d < 100\n", num) // will not be executed default: fmt.Printf("I don't know", num) } GO programming language num := 10; switch { case num >= 0 && num <= 50: fmt.Printf("%d < 50 \n", num) // print: 10 < 50 fallthrough case num < 100: fmt.Printf("%d < 100 \n", num) //print: 10 < 100 default: fmt.Printf("I don't know", num) }
26
Overvie w - Delay (defer) is a fairly new concept in flow control. It allows a command to be called but does not execute immediately and delays until the surrounding commands return results - The commands that are called via the defer keyword will be put on a stack, work following last-in-first-out mechanism Code defer package main import "fmt" func main() { defer fmt.Println("World") // Delay print: "World" fmt.Println("Hello") // Print: "Hello" // output : Hello World } GO programming language
27
Overview - Slice is a reference to Array, it describes part (or all) Array. It has dynamic size so it is often used more than Array. - Slice can be created from an Array by providing 2 indexes (low and high) to locate the element in Array. - A slice will have two attributes: length and capacity. Length is the number of elements in Slice, capacity is the number of elements in Array that the Slice refers to (starting from the first element of Slice). To get the length we use len(), to get the capacity, we use cap() - Because slices are only references to Array, changing the value of slices will change the value of the Array. If there are multiple slices that reference an Array, changing the value of a slice can change the value of other slices. Slices GO programming language
28
Code for Slices GO programming language s := []int{2, 3, 5, 7, 11, 13} s = s[0:0] // s = [], len(s) = 0, cap(s) = 6 s = s[0:4] // s = [2, 3, 5, 7], len(s) = 4, cap(s) = 6 s = s[2:4] // s = [5, 7], len(s) = 2, cap(s) = 4
29
Over view - Array in GO is similar to other languages, but it has fixed size and all elements must be of the same data type - Unlike most other languages, Array in GO is not a reference type but a value type. When assigning its value to a new variable, it will create a copy of the old Array, and any changes to the new Array will not affect the old Array Structs package main import ( "fmt" ) type Student struct { name string age int } func main() { s1 := Student{"Steve", 30} s2 := Student{"Steve", 30} s3 := Student{"Job", 30} if s1 == s2 { fmt.Println("s1 = s2") } else { fmt.Println("s1 != s2") } GO programming language Code
30
Overview - Map is a set of elements stored as key - value. The key in the map has a comparable and non-duplicate data type. To create a map, use the make() function with the following formula: make(map[type of key]type of value) - To delete the element in the map, we use the delete() function and provide the key of the element to be deleted. - To access the element in the map, we call the map with the key of the element. If that key does not exist, we will get the value zero value (depending on the data type). The first value is the same as the above example, the second value will be true if the element is in map and false if the element does not exist. Maps GO programming language
31
Code for Maps GO programming language var demoMap map[string]int if demoMap == nil { fmt.Println("Map has nil value.") demoMap = make(map[string]int) } languages := make(map[string]float32) languages["go"] = 0.63 languages["java"] = 1.03 delete(languages, "go") m := make(map[string]int) m["Answer"] = 42 delete(m, "Answer") fmt.Println(m["Answer"]) v, ok := m["Answer"] fmt.Println("Value of element: ", v) // v= 0 fmt.Println("Exist or not ", ok) // ok = false
32
Over view We can use struct instead of class. However, struct only has properties and no methods. To apply the method as other object-oriented languages, we will need to declare the function with a special parameter called the receiver argument. The receiver argument is in the middle of the func keyword and the function name, it will indicate a type (usually a struct) to apply this function as a method. Structs package main import ( "fmt" "math" ) type Vertex struct { X, Y float64 } // Creat method abs() for struct Vertex(receiver argument) func (v Vertex) Abs() float64 { return math.Sqrt(v.X*v.X + v.Y*v.Y) } func main() { v := Vertex{3, 4} fmt.Println(v.Abs()) } GO programming language Code
33
Overview - Interface is a definition of method sets that an object needs to comply with (similar to other object-oriented languages). When a type contains methods as declared in the interface, it is deploying that interface. - The interface implementation type must have a full set of methods defined in the interface. - An interface without any method is called an Emtpy Interface. The empty interface can store all types of data, so it is often used in the case of processing functions that need dynamic parameters (all data types). Interfaces GO programming language
34
Code for Interfaces GO programming language package main import "fmt" // Interface I has method M() type I interface { M() } type T struct { S string } // Define method M() for struct T func (t T) M() { fmt.Println(t.S) } func main() { // init variable i with type interface I var i I = T{"hello"} // call method M() i.M() }
35
Code for Interfaces (continue) GO programming language package main import "fmt" type I interface { M(), N() } type T struct { S string } func (t T) M() { fmt.Println(t.S) } func main() { var i I = T{"hello"} i.M() // The result will be an error because of struct T implement interface I,but there are not enough declared methods (missing method N ()) }
36
Code for Interfaces (continue) GO programming language package main import "fmt" func main() { var i interface{} // Empty interface i = 42 describe(i) i = "hello" describe(i) } // we can pass all data type in to function describe func describe(i interface{}) { fmt.Printf("(%v, %T)\n", i, i) }
37
Thank You
Similar presentations
© 2025 SlidePlayer.com Inc.
All rights reserved.