A Brief History

"Robert Griesemer, Rob Pike and Ken Thompson started sketching the goals for a new language on the white board on September 21, 2007. Within a few days the goals had settled into a plan to do something and a fair idea of what it would be. Design continued part-time in parallel with unrelated work. By January 2008, Ken had started work on a compiler with which to explore ideas; it generated C code as its output. By mid-year the language had become a full-time project and had settled enough to attempt a production compiler. In May 2008, Ian Taylor independently started on a GCC front end for Go using the draft specification. Russ Cox joined in late 2008 and helped move the language and libraries from prototype to reality.

 

Go became a public open source project on November 10, 2009. Many people from the community have contributed ideas, discussions, and code." - The Go FAQ

Before We Start - Floobits!

 

All material in this class will be done using a shared text editor so all students can be involved writing code. Jump in and code with us!

 

https://floobits.com/zquestz/GoSF

Go Tooling

- Environment Variables -

     • $GOPATH - path to your Go source code and packages.

     • $GOBIN - path to your Go built binaries.

- Binaries -

go - http://golang.org/cmd/go/​

     • go build [-o output] [-i] [build flags] [packages]

     • go install [build flags] [packages]

     • go test [-c] [-i] [build and test flags] [packages] [flags for test binary]

godoc - https://godoc.org

     • godoc -http=:6060

gofmt - https://golang.org/cmd/gofmt

Go Testing

Read up, for the rest of this session we will be writing tests. 

go test package - http://golang.org/pkg/testing/

Basics of Go

• Types (Numbers, Strings, Booleans) 
• Variables (Scope, Multiple Assignment, Constants) 
• Control Structures (For, If, Switch) 
• Arrays, Slices, Maps

• Error handling 
• Functions (Basic Syntax, Variadic, Closures)

• More Functions (Defer, Panic, Recover) 
• Pointers/Structs/Interfaces 
• Concurency (Goroutines, Channels) 

Types

Go comes with many default types. Here are a few you will use often. For reference you can get definitions for all the types at: http://golang.org/pkg/builtin/​

  • Integers - int, int8, int16, int32, rune, int64, uint, uint8, uint16, uint32, uint64
  • Floating Point - float32, float64
  • Complex Numbers - complex64, complex132
  • Bytes - byte
  • Strings - string
  • Booleans - bool

Variables/Constants

Variable declarations and details are documented at http://golang.org/ref/spec

- Examples -

  • var i int
    
  • var anotherint int = 5
  • short := "This is a shorthand variable declaration"
  • var1, err := SomeFunction() // This function returns 2 values.
  • const a = 5

Control Structures

In Go, control structures are actually simple. The only looping construct is a for loop. There are also if and switch (case) statements.

  • for i := 0; i < 5; i++ {
        fmt.Println("Value of i is now:", i)
       } // Regular for loop.
  • for sum < 10 {
        fmt.Println(sum += sum)
       } // While style for loop
  • if city == "San Francisco" { fmt.Println("Best city in the states!") }
  • i := 5
       switch i {
       case 5: fmt.Println("Yep")
       default: fmt.Println("Nope")
       }
    

Arrays/Slices/Maps

Slices and maps are obviously very important. For more documentation on slices and maps visit http://blog.golang.org/go-slices-usage-and-internals​ and http://blog.golang.org/go-maps-in-action​

  • []string{"item1", "item2"} // Slice
  • [2]string{"item1", "item2"} // Array
  • []int{1, 2}
  • var s []byte
       s = make([]byte, 5, 5)
       // s == []byte{0, 0, 0, 0, 0}
  • m := make(map[string]string) // Map with string key and value.
  • m["foo"] = "bar" // Set item on map.
  • delete(m, "foo") // Delete key from map
  • i, ok := m["route"] // Check if key exists on map

Error Handling

Go has a great pattern for handling errors. Functions that could error out include an error object in the return value when something goes wrong. For instance:

 

func MyFunction() error {
​  value, err := SomeFunction()
  if err != nil {
     return err
  }
  return nil

}

Functions

There are quite a few ways to define functions in Go. I would recommend reading http://jordanorelli.com/post/42369331748/function-types-in-go-golang​ if you are interested in a more complete overview.

  • func Foo(s string) { } // takes a string and has no return value.

  • func Bar(s string) string { } // takes and returns a string

  • func FooBar(s ...string) string { } // takes unlimited strings and returns a string

  • var a := func () {} // assigns a function to a variable.

  • a := 5
          var b = func() {
            fmt.Println(a)
          } // closure
          b() // prints a

Defer, Panic, Recover

First, for an overview of defer, panic and recover check out this excellent article from the Go Blog. http://blog.golang.org/defer-panic-and-recover

- Defer Example -

srcName := "/some/file/path/file.txt"
src, err := os.Open(srcName)
if err != nil { return }
defer src.Close()

- Panic Example -

​panic("Something very bad happened, exit now.")

- Recover Example - 

​defer func() {

  if r := recover(); r != nil { fmt.Println("Recovered in f", r) }

}()

Pointers

func addOne(x int) int {
    x = x + 1
    return x
}

func addOnePointer(x *int) int {
    *x = *x + 1
    return *x
}

func main() {
    x := 1
    fmt.Printf("addOne(): x+1=%d; x=%d\n", addOne(x), x)
    fmt.Printf("addOnePointer(): x+1=%d; x=%d\n", addOnePointer(&x), x)
}

Interfaces

type Greeter interface {
    Greet() string
}

type WorldGreeter struct{}

func (g WorldGreeter) Greet() string {
    return "Hello world!"
}

func printGreeting(g Greeter) {
    fmt.Println(g.Greet())
}

func main() {
    g1 := WorldGreeter{}
    printGreeting(g1)
}

Go Routines

func doSomeStuff(n int, wg *sync.WaitGroup) {
    duration := time.Millisecond * time.Duration(rand.Intn(1000))
    time.Sleep(duration)
    fmt.Printf("%d finished\n", n)
    wg.Done()
}

func main() {
    var wg sync.WaitGroup

    for i := 0; i < 10; i++ {
        wg.Add(1)
        go doSomeStuff(i, &wg)
    }

    wg.Wait()
}

Channels

type Ball struct{ hits int }

func main() {
    table := make(chan *Ball)
    go player("ping", table)
    go player("pong", table)

    table <- new(Ball) // game on; toss the ball
    time.Sleep(1 * time.Second)
    <-table // game over; grab the ball
}

func player(name string, table chan *Ball) {
    for {
        ball := <-table
        ball.hits++
        fmt.Println(name, ball.hits)
        time.Sleep(100 * time.Millisecond)
        table <- ball
    }
}

Intro To Go Packages

Next Steps

"A Tour Of Go" provides an excellent interactive tutorial. http://tour.golang.org/

"An Introduction to Programming In Go" is an online reference for new developers. http://www.golang-book.com/

Check out third party packages on Github!

Build apps. Then build more apps.

Programming in Go

By Josh Ellithorpe

Programming in Go

A brief introduction to the Go programming language.

  • 1,866