Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Introduction to Go programming language

3,522 views

Published on

Quick overview of Google Go programming language

Published in: Technology

Introduction to Go programming language

  1. 1. Introduction toGoSlawomir Dorzak@sdorzak
  2. 2. About this presentation● The point is to give you a "taste" of Go, notto teach you how to programming in it● I assume you know what an array and apointer is● Im not a Go expert
  3. 3. Quick history● Invented by Robert Griesemer, Rob Pikeand Ken Thompson in 2007 (public in 09)● Born out of a need for ease of programmingcombined with type safety and portability● Other goals:○ Easy to learn○ Type safety and memory safety○ Easy concurrency via channels and "goroutines"○ Low latency garbage collection○ Fast compilation
  4. 4. Who is Ken Thompson?
  5. 5. Some companies using Go● Canonical● BBC● Heroku● CloudFoundry● CloudFlare● Bit.ly● Google
  6. 6. IDE options● Sublime Text 2● IntelliJ● LiteIDE● Intype (Windows only)● Netbeans● Eclipse● TextMate● Komodo● Zeus (Windows only)
  7. 7. Syntax overview● It looks similar to C● End of line semicolons are optional● Variable declarations are optional○ variable name is followed by its type■ var s string○ variables can also be declared by initialization■ i := 0● Type conversions must be explicit● Visibility is controlled using capitalization eg.○ func Foo() will be publicly visible outside thedefining package○ func bar() will be private
  8. 8. Interesting caveats● Unused variables are a compilation error● Unused import directives also● No classes - Go is a procedural language● No overloading● No inheritance
  9. 9. Control structures● If● For● SwitchThats it!
  10. 10. Control structures samplesif v := math.Pow(x, n); v < lim {return v} else {fmt.Printf("%g >= %gn", v, lim)}
  11. 11. Control structures samplesfor i := 0; i < 10; i++ {sum += i}for sum < 1000 {sum += sum}for {}
  12. 12. Control structures samplest := time.Now()switch {case t.Hour() < 12:fmt.Println("Good morning!")case t.Hour() < 17:fmt.Println("Good afternoon.")default:fmt.Println("Good evening.")}
  13. 13. Types● Boolean - bool● Numeric - uint8 to uint64, int8 to int64, uint, int, float32, float64,complex64, complex128, byte, rune● String - string● Array eg. [5]byte, Slice eg. make([]int, 50, 100), Map eg. map[string]int● Struct - struct● Pointer - *● Function - func● Interface - interface● Channel - chan
  14. 14. Array● Numbered sequence of elements of a singletype● Fixed size● Always one dimensional but can becombined● eg.○ [32]byte○ [2][8]int○ [5]myStruct○ [3]SomePublicInterface○ [2]struct { x, y int32 }○ b := [...]string{"Penn", "Teller"}
  15. 15. Slice● Represents a segment of an array● Like array - slice is one dimensional● Slice does not have a fixed length● Once initialized is always associated withand underlying array● Creating a slice:○ make([]int, 50, 100)○ new([100]int)[0:50]○ letters := []string{"a", "b", "c", "d"}
  16. 16. Map● Its a hash table implementeation in Go● Provides fast lookup by given key● Key can be any type that is comparable● Value can be any type including anothermap● Order is not guaranteed● Maps are not safe for concurrent use!m := make(map[string]int)m["val1"] = 1m["val2"] = 2for key, value := range m {fmt.Println("Key:", key, "Value:", value)}
  17. 17. Struct● Structs are declared using struct keyword● Only fields can be defined inside a structtype Vertex struct {X intY int}p := Vertex{1, 2}
  18. 18. Function● Can return multiple values● Unlike in C you can return address of a localvariable● Functions can be "attached" to a struct orinterfacefunc NewFile(fd int, name string) *File {if fd < 0 {return nil}f := File{fd, name, nil, 0}return &f}func (v Vertex)Print() string{}
  19. 19. Sample codepackage mainimport "fmt"// fib returns a function that returns successive Fibonacci numbers.func fib() func() int {a, b := 0, 1return func() int {a, b = b, a+breturn a}}func main() {f := fib()// Function calls are evaluated left-to-right.fmt.Println(f(), f(), f(), f(), f())}
  20. 20. Interface● Used to specify a behavior of an object● A type can implement multiple interfaces● Interfaces can be used in place of concretetypes● Empty interface is met by any typetype Stringer interface {ToString() string}
  21. 21. Embedding● a bit like inheritance● allows to combine structs or interfacestype Reader interface {Read(p []byte) (n int, err error)}type Writer interface {Write(p []byte) (n int, err error)}// ReadWriter is the interface that combines the Reader and Writer interfaces.type ReadWriter interface {ReaderWriter}
  22. 22. Channels and goroutines"Do not communicate by sharing memory;instead, share memory by communicating"● goroutine - is a lightweight concurrentfunction (like thread)● remove complexities of thread management● channels are used for communicatingbetween goroutines● they can be buffered or unbuffered
  23. 23. Example of using goroutines andchannelsfunc sum(a []int, c chan int) {sum := 0for _, v := range a {sum += v}c <- sum // send sum to c}func main() {a := []int{7, 2, 8, -9, 4, 0}c := make(chan int)go sum(a[:len(a)/2], c)go sum(a[len(a)/2:], c)x, y := <-c, <-c // receive from cfmt.Println(x, y, x+y)}
  24. 24. What is go good for?"large programs written by many developers,growing over time to support networkedservices in the cloud: in short, server software"-- Rob Pike
  25. 25. Resources● http://tour.golang.org● http://golangtutorials.blogspot.ie● http://golang.org/doc/effective_go.htm● http://www.golang-book.com● https://github.com/golang-samples

×