Golang preso
-
Upload
christopher-foresman -
Category
Documents
-
view
280 -
download
1
Transcript of Golang preso
This is what our presentations
should look like
JAN. 2, 2015
Go: Concurrency
is Built In
MAY 14,, 2015
What’s Similar?GOLANG vs PYTHON
Similarities with Python
• Can be “imperative” or “object-oriented”• Great for writing web servers (guess what my day job is)• Arrays use Python-like slicing• Easy iteration over arrays (lists) and maps (dicts) using range• Multiple return values from functions• Package management (go get vs. pip install)• Anonymous functions
3
What’s Different?GOLANG vs PYTHON
Differences with Python
• Structs vs. objects• Strongly-typed• Compiled, C-like syntax (ugh)• Interface vs inheritance• Modules vs. packages• camelCase• CapitalName : capitalName :: attribute : _attribute• return errors instead of raising exceptions
5
Go has no GILGOLANG vs PYTHON
It’s not bolted on like asyncio, or hacked in à la Tornado.
The Go runtime has a scheduler that automatically schedules multiple concurrent operations efficiently and automatically.
It’s so efficient, it doesn’t even guarantee all concurrent operations even run!
Concurrency is built into the runtime
7
Concurrency
• goroutines• defer• wait groups (via sync package)• channels
8
Everything in Go is a “goroutine”, including main(). Dispatch a function to execute in a separate goroutine using the go keyword:func doStuff(string a) { fmt.Println(a)}
func main() { var a string = “Python is cool!” go doStuff(a)}
goroutines
9
You can defer execution of a line until the end of a function:func processFile(string filename) bool, error {
f, err := os.Open(filename)defer f.close()if err != nil {
return false, err}...return true, nil
}
defer
10
Fire off multiple goroutines, wait until they are done before moving on:var wg sync.WaitGroupvar urls = []string{
"http://www.golang.org/","http://www.google.com","http://www.somestupidname.com/",
}for _, url := range urls {
wg.Add(1)go func(url string) {
defer wg.Done()http.Get(url)
}(url)}wg.Wait()
wait group
11
Allow communication/synchronization between goroutines:func pinger(c chan string) {
for i := 0; ; i++ {
c <- "ping"
}
}
func printer(c chan string) {
for {
msg := <- c
fmt.Println(msg)
time.Sleep(time.Second * 1)
}
}
channels
12
func main() {
var c chan string = make(chan string)
go pinger(c)
go printer(c)
var input string
fmt.Scanln(&input)
}
13
“Object-oriented design is the roman numerals of computing.”GOLANG DESIGNER ROB PIKE
Use the best tool for the job.MY ADVICE:
http://tour.golang.orgSTART HERE