Josh Ellithorpe
I like terminal prompts.
"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
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!
- 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
Read up, for the rest of this session we will be writing tests.
go test package - http://golang.org/pkg/testing/
• 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)
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/
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
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")
}
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
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
}
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
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) }
}()
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) }
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)
}
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() }
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
}
}
• fmt - https://godoc.org/fmt
• strings - https://godoc.org/strings
• io/ioutil - https://godoc.org/io/ioutil
• os - https://godoc.org/os
• errors - https://godoc.org/errors
• encoding/json - https://godoc.org/encoding/json
• net/http - https://godoc.org/net/http
• sync - https://godoc.org/sync
• flag - https://godoc.org/flag
"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.
By Josh Ellithorpe
A brief introduction to the Go programming language.