Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Introduction to Go

The Guild
September 05, 2013

Introduction to Go

Pascal Widdershoven gives The Guild (http://theguild.nl) an introduction to and possible uses of Go, a new programming language by Google. Video available at https://vimeo.com/74244545

The Guild

September 05, 2013
Tweet

More Decks by The Guild

Other Decks in Programming

Transcript

  1. • Young, open source, modern programming language inspired by C

    • Developed internally at Google, beginning in 2007 • Officially announced in November 2009 • Now at 1.1 What is Go?
  2. • Statically typed, garbage collected • Concurrency as a first

    class citizen • Rich standard library, “batteries included” • Fast compilation, cross platform Key features
  3. package main import "fmt" // fib returns a function that

    returns // successive Fibonacci numbers. func fib() func() int { a, b := 0, 1 return func() int { a, b = b, a+b return a } } func main() { f := fib() // Function calls are evaluated left-to-right. fmt.Println(f(), f(), f(), f(), f()) } Closure Type inference Look ma, no semicolons!
  4. • Goroutines can be thought of as cheap threads •

    Goroutines communicate through channels Goroutines
  5. func main() { c1 := produce("Chan 1") c2 := produce("Chan

    2") for i := 0 ; i < 10 ; i++ { select { case msg1 := <- c1: fmt.Println(msg1) case msg2 := <- c2: fmt.Println(msg2) } } } func produce(cName string) <-chan string { c := make(chan string) go func() { for i := 0; ; i++ { c <- fmt.Sprintf("Ping %d on %s", i, cName) time.Sleep(time.Duration(rand.Intn(3)) * time.Second) } }() return c } Producer Consumer Create producers Goroutine
  6. Objected oriented? • Yes and no • No type hierarchy

    • Go structs are a bit like classes • Functions can be defined on structs
  7. type Person struct { Firstname string Lastname string Age int

    } func(p *Person) Fullname() string { return fmt.Sprintf("%s %s", p.Firstname, p.Lastname) } func main() { p := Person{"Pascal", "Widdershoven", 24} fmt.Println(p.Fullname()) // => Pascal Widdershoven } Struct definition Method receiver Call method on struct
  8. Error handling • No exceptions! • Functions return error objects

    dir, err := os.Open(".") if err != nil { return } • Multiple return values are used extensively
  9. The ugly • Features not implemented (yet) • Package management

    • Immature eco-system • Lack of tooling