Go Fundamentals
Agenda
● What is Go?
○ Guiding Principles
■ Why Simplicity is Important?
■ Why Readability is Important?
● Why You Should Learn Go?
○ Interest Over Time
○ Go In Production
○ What still needs work
● Syntax Overview
○ Hello World
● Go’s Concurrency Model
○ A Word on CSP And Communications Model
○ The Go Runtime
○ Goroutines
■ What Are Goroutines?
■ Goroutines VS. Threads
○ Channels
○ Examples
What Is Go?
Go (golang) is a programming language developed at
Google[9] in 2007 by Robert Griesemer, Rob Pike, and
Ken Thompson.[7]
Go is a general-purpose language designed with
systems programming in mind.
● strongly typed and garbage-collected and has
● explicit support for concurrent programming.
● Programs are constructed from packages, whose
properties allow efficient management of
dependencies.
● The existing implementations use a traditional
compile/link model to generate executable
binaries.
What Is Go?
Motivation:
● Needed a better language for what they do at Google
● Personal motivation: Wanted a clean, small, compiled language with
modern features.
● Clear about what was wrong: Complexity, missing concurrency support,
lack of scalability, insane build times.
● Good ideas about how to address issues.
● Unpolished thoughts about the rest.
● Three experienced people's insights on how not to do it.
Check out this lecture
History
● Project starts at Google in 2007 (by Griesemer, Pike, Thompson)
● Open source release in November 2009
● More than 250 contributors join the project
● Version 1.0 release in March 2012
Guiding Principles
Guiding principles
● Simplicity, safety, and readability are paramount.
● Striving for orthogonality in design.
● Minimal: One way to write a piece of code.
● It's about expressing algorithms, not the type
system.
Why Simplicity Is Important?
Simple Calculation The Ruby Way:
result = 0
for i in 0..10
result += i
end
(1..10).inject(0) { |result, element| result + element }
=> 55
(1..10).reduce(0) { |result, element| result + element }
=> 55
result = 0
(1..10).each{ |element| result += element }
=> 55
result = 0
(1..10).map { |element| result += element }
=> 55
This is without while, until and regular for
loops….
It's a bit overdoing it, but you get the picture..
Why Simplicity Is Important?
Simple Calculation The Gopher Way:
sum := 0
for i := 0; i < 10; i++ {
sum += i
}
Why Readability Is Important?
• If a language has too many features, you waste time choosing which
ones to use.
• Then implement, refine, possibly rethink and redo.
• Later, "Why does the code work this way?"
• The code is harder to understand simply because it is using a more
complex language.
• Preferable to have just one way, or at least fewer, simpler ways.
• Features add complexity. We want simplicity.
• Features hurt readability. We want readability.
• Readability is paramount.
Why Readability Is Important?
• Readable means Reliable
• Readable code is reliable code.
• It's easier to understand.
• It's easier to work on.
• If it breaks, it's easier to fix.
• If the language is complicated:
– You must understand more things to read and work on the code.
– You must understand more things to debug and fix it.
A key tradeoff: More fun to write, or less work to maintain
Interpreted VS Statically Compiled
Interpreted Languages
• Execute instructions directly,
without previously compiling a
program into machine-
language instructions.
• The interpreter executes the
program directly, translating
each statement into a sequence
of one or more subroutines
already compiled into machine
code.
• Reflection
• Dynamic Typing - the process of
verifying the type safety of a
program at runtime
Compiled Languages
• Quicker than those translated
at run time, due to the
overhead of the translation
process.
• Static Typing - finding type
errors reliably at compile time,
which should increase the
reliability of the delivered
program
Interpreted VS Statically Compiled
Interpreted (High Level) Languages
• More Readable (Usually)
• Portable - Platform
Independent Like JVM
• Powerfull
• Flexible
• Slower execution compared to
direct native machine code
execution on the host CPU.
• Easily to Reverse Engineer
Some Examples:
Ruby, Python, Javascript, Perl,
Scheme and many more!
Compiled (Low Level) Languages
• Not platform-independent
• Adding one more step to
deployment and debugging
process
Some Examples:
C/C++, Java, C#, Go, Visual basic,
Haskell, Erlang, Rust and others
So, Why You Should Learn Go?
• Modern
• Compact, concise, general-
purpose
• Imperative statically type-
checked, dynamically type-safe
• Garbage-collected
• Compiles to native code,
statically linked
• Fast compilation, efficient
execution
• Multi Platform Support
• Extensive Standard Library
Designed by programmers for programmers!
Interest Over Time
Go In Production
Go Helps Google
• Slow builds
• Uncontrolled dependencies
• Each programmer using a different subset of the language
• Poor program understanding (code hard to read, poorly documented,
and so on)
• Duplication of effort
• Cost of updates
• Version skew
• Difficulty of writing automatic tools
• Cross-language builds
Not All Is Good In The Hood
● Error handling / no Exceptions
● No generics
● Stuck in 70’s
● No OOP - No Inheritance, You can Embed
● Version Management of Dependencies - Some Solutions but should be
released in the next Go release
● Getting time to get used to if you come from a Proper OOP Language.
Hello World
package main
import "fmt"
func main() {
fmt.Println("Greetings, fellow gopher")
}
Syntax Overview
Golang Tour
Go’s Concurrency Model
Why We Should care about languages that use concurrency?
The modern world is parallel
● Multicore.
● Networks.
● Clouds of CPUs.
● Loads of users.
● Our technology should help.
That's where concurrency comes in.
Go’s Concurrency Model
Go Concurrency relies on Tony Hoare's
Communicating sequential processes article
from 1978
Message Passing Model with Interprocess
communication
The Most important slogan of all:
“Do not communicate by sharing
memory; instead, share memory by
communicating.”
Go’s Concurrency Model
Traditional threading models (commonly used when writing Java, C++,
and Python programs, for example) require the programmer to
communicate between threads using shared memory. Typically, shared
data structures are protected by locks, and threads will contend over
those locks to access the data
Go provides:
● Concurrent execution (goroutines)
● Synchronization and messaging (channels)
● Multi-way concurrent control (select)
● (and Also mutex for old school locking)
The Go Runtime
Package runtime contains operations that interact with Go's runtime system,
such as functions to control goroutines.
it contains a runtime which provides garbage collection, reflection and many
other features.
Why Go’s Executable Are HUGE!?
Goroutines
A goroutine is a function that is capable of running concurrently with other functions.
To create a goroutine we use the keyword go followed by a function invocation:
So This:
func main() {
fmt.Println("start")
doSomething()
fmt.Println("end")
}
Becomes:
func main() {
fmt.Println("start")
go doSomething()
fmt.Println("end")
}
Goroutines VS. Threads
• Memory Consumption - 2kb vs 1mb
• Setup and teardown costs - No Resources from the os, Only the runtime
• Switching costs - Registers Switching
• How goroutines are executed - Runtime allocated os threads and distribute
goroutines on them
Goroutines VS. Threads
• Goroutines blocking
Goroutines are cheap and do not cause the thread on which they are multiplexed to block if they
are blocked on
– network input
– sleeping
– channel operations or
– blocking on primitives in the sync package.
Even if tens of thousands of goroutines have been spawned, it's not a waste of system
resources if most of them are blocked on one of these since the runtime schedules another
goroutine instead.
In simple terms, goroutines are a lightweight abstraction over threads.
A Go programmer does not deal with threads, and similarly the OS is not aware of the existence
of goroutines. From the OS's perspective, a Go program will behave like an event-driven C
program. [5]
Examples Of Goroutines
Concurrency for beginners
Channels
Channels are a staple of
concurrency built right into the Go
language, and provide a way for
goroutines to synchronise, and
share information.
Example Of Channels
Ping Pong
Cool Example using Goroutines
Thank You.

Go fundamentals

  • 1.
  • 2.
    Agenda ● What isGo? ○ Guiding Principles ■ Why Simplicity is Important? ■ Why Readability is Important? ● Why You Should Learn Go? ○ Interest Over Time ○ Go In Production ○ What still needs work ● Syntax Overview ○ Hello World ● Go’s Concurrency Model ○ A Word on CSP And Communications Model ○ The Go Runtime ○ Goroutines ■ What Are Goroutines? ■ Goroutines VS. Threads ○ Channels ○ Examples
  • 3.
    What Is Go? Go(golang) is a programming language developed at Google[9] in 2007 by Robert Griesemer, Rob Pike, and Ken Thompson.[7] Go is a general-purpose language designed with systems programming in mind. ● strongly typed and garbage-collected and has ● explicit support for concurrent programming. ● Programs are constructed from packages, whose properties allow efficient management of dependencies. ● The existing implementations use a traditional compile/link model to generate executable binaries.
  • 4.
    What Is Go? Motivation: ●Needed a better language for what they do at Google ● Personal motivation: Wanted a clean, small, compiled language with modern features. ● Clear about what was wrong: Complexity, missing concurrency support, lack of scalability, insane build times. ● Good ideas about how to address issues. ● Unpolished thoughts about the rest. ● Three experienced people's insights on how not to do it. Check out this lecture
  • 5.
    History ● Project startsat Google in 2007 (by Griesemer, Pike, Thompson) ● Open source release in November 2009 ● More than 250 contributors join the project ● Version 1.0 release in March 2012
  • 6.
    Guiding Principles Guiding principles ●Simplicity, safety, and readability are paramount. ● Striving for orthogonality in design. ● Minimal: One way to write a piece of code. ● It's about expressing algorithms, not the type system.
  • 7.
    Why Simplicity IsImportant? Simple Calculation The Ruby Way: result = 0 for i in 0..10 result += i end (1..10).inject(0) { |result, element| result + element } => 55 (1..10).reduce(0) { |result, element| result + element } => 55 result = 0 (1..10).each{ |element| result += element } => 55 result = 0 (1..10).map { |element| result += element } => 55 This is without while, until and regular for loops…. It's a bit overdoing it, but you get the picture..
  • 8.
    Why Simplicity IsImportant? Simple Calculation The Gopher Way: sum := 0 for i := 0; i < 10; i++ { sum += i }
  • 9.
    Why Readability IsImportant? • If a language has too many features, you waste time choosing which ones to use. • Then implement, refine, possibly rethink and redo. • Later, "Why does the code work this way?" • The code is harder to understand simply because it is using a more complex language. • Preferable to have just one way, or at least fewer, simpler ways. • Features add complexity. We want simplicity. • Features hurt readability. We want readability. • Readability is paramount.
  • 10.
    Why Readability IsImportant? • Readable means Reliable • Readable code is reliable code. • It's easier to understand. • It's easier to work on. • If it breaks, it's easier to fix. • If the language is complicated: – You must understand more things to read and work on the code. – You must understand more things to debug and fix it. A key tradeoff: More fun to write, or less work to maintain
  • 11.
    Interpreted VS StaticallyCompiled Interpreted Languages • Execute instructions directly, without previously compiling a program into machine- language instructions. • The interpreter executes the program directly, translating each statement into a sequence of one or more subroutines already compiled into machine code. • Reflection • Dynamic Typing - the process of verifying the type safety of a program at runtime Compiled Languages • Quicker than those translated at run time, due to the overhead of the translation process. • Static Typing - finding type errors reliably at compile time, which should increase the reliability of the delivered program
  • 12.
    Interpreted VS StaticallyCompiled Interpreted (High Level) Languages • More Readable (Usually) • Portable - Platform Independent Like JVM • Powerfull • Flexible • Slower execution compared to direct native machine code execution on the host CPU. • Easily to Reverse Engineer Some Examples: Ruby, Python, Javascript, Perl, Scheme and many more! Compiled (Low Level) Languages • Not platform-independent • Adding one more step to deployment and debugging process Some Examples: C/C++, Java, C#, Go, Visual basic, Haskell, Erlang, Rust and others
  • 13.
    So, Why YouShould Learn Go? • Modern • Compact, concise, general- purpose • Imperative statically type- checked, dynamically type-safe • Garbage-collected • Compiles to native code, statically linked • Fast compilation, efficient execution • Multi Platform Support • Extensive Standard Library Designed by programmers for programmers!
  • 14.
  • 15.
  • 16.
    Go Helps Google •Slow builds • Uncontrolled dependencies • Each programmer using a different subset of the language • Poor program understanding (code hard to read, poorly documented, and so on) • Duplication of effort • Cost of updates • Version skew • Difficulty of writing automatic tools • Cross-language builds
  • 17.
    Not All IsGood In The Hood ● Error handling / no Exceptions ● No generics ● Stuck in 70’s ● No OOP - No Inheritance, You can Embed ● Version Management of Dependencies - Some Solutions but should be released in the next Go release ● Getting time to get used to if you come from a Proper OOP Language.
  • 18.
    Hello World package main import"fmt" func main() { fmt.Println("Greetings, fellow gopher") }
  • 19.
  • 20.
    Go’s Concurrency Model WhyWe Should care about languages that use concurrency? The modern world is parallel ● Multicore. ● Networks. ● Clouds of CPUs. ● Loads of users. ● Our technology should help. That's where concurrency comes in.
  • 21.
    Go’s Concurrency Model GoConcurrency relies on Tony Hoare's Communicating sequential processes article from 1978 Message Passing Model with Interprocess communication The Most important slogan of all: “Do not communicate by sharing memory; instead, share memory by communicating.”
  • 22.
    Go’s Concurrency Model Traditionalthreading models (commonly used when writing Java, C++, and Python programs, for example) require the programmer to communicate between threads using shared memory. Typically, shared data structures are protected by locks, and threads will contend over those locks to access the data Go provides: ● Concurrent execution (goroutines) ● Synchronization and messaging (channels) ● Multi-way concurrent control (select) ● (and Also mutex for old school locking)
  • 23.
    The Go Runtime Packageruntime contains operations that interact with Go's runtime system, such as functions to control goroutines. it contains a runtime which provides garbage collection, reflection and many other features. Why Go’s Executable Are HUGE!?
  • 24.
    Goroutines A goroutine isa function that is capable of running concurrently with other functions. To create a goroutine we use the keyword go followed by a function invocation: So This: func main() { fmt.Println("start") doSomething() fmt.Println("end") } Becomes: func main() { fmt.Println("start") go doSomething() fmt.Println("end") }
  • 25.
    Goroutines VS. Threads •Memory Consumption - 2kb vs 1mb • Setup and teardown costs - No Resources from the os, Only the runtime • Switching costs - Registers Switching • How goroutines are executed - Runtime allocated os threads and distribute goroutines on them
  • 26.
    Goroutines VS. Threads •Goroutines blocking Goroutines are cheap and do not cause the thread on which they are multiplexed to block if they are blocked on – network input – sleeping – channel operations or – blocking on primitives in the sync package. Even if tens of thousands of goroutines have been spawned, it's not a waste of system resources if most of them are blocked on one of these since the runtime schedules another goroutine instead. In simple terms, goroutines are a lightweight abstraction over threads. A Go programmer does not deal with threads, and similarly the OS is not aware of the existence of goroutines. From the OS's perspective, a Go program will behave like an event-driven C program. [5]
  • 27.
  • 28.
    Channels Channels are astaple of concurrency built right into the Go language, and provide a way for goroutines to synchronise, and share information.
  • 29.
    Example Of Channels PingPong Cool Example using Goroutines
  • 30.

Editor's Notes

  • #8 Large Codebase and many Developers its important that code will be readable and easy to understand for new developers
  • #10 https://talks.golang.org/2015/simplicity-is-complicated.slide#1
  • #11 https://talks.golang.org/2015/simplicity-is-complicated.slide#1
  • #16 https://github.com/golang/go/wiki/GoUsers
  • #18 https://divan.github.io/posts/go_complain_howto/
  • #19 Main Package, Imports, Main Func
  • #20 http://tour.golang.org/welcome/1
  • #22  Go's concurrency primitives - goroutines and channels - provide an elegant and distinct means of structuring concurrent software. (These concepts have an interesting history that begins with C. A. R. Hoare's Communicating Sequential Processes.) Instead of explicitly using locks to mediate access to shared data, Go encourages the use of channels to pass references to data between goroutines. This approach ensures that only one goroutine has access to the data at a given time. The concept is summarized in the document
  • #25 http://divan.github.io/posts/go_concurrency_visualize/
  • #26 http://blog.nindalf.com/how-goroutines-work/ Memory Consumption The creation of a goroutine does not require much memory - only 2kB of stack space. They grow by allocating and freeing heap storage as required.[2][3] Threads on the other hand start out at 1Mb (500 times more), along with a region of memory called a guard page that acts as a guard between one thread's memory and another.[7] A server handling incoming requests can therefore create one goroutine per request without a problem, but one thread per request will eventually lead to the dreaded OutOfMemoryError. Setup and teardown costs Threads have significant setup and teardown costs because it has to request resources from the OS and return it once its done. The workaround to this problem is to maintain a pool of threads. In contrast, goroutines are created and destroyed by the runtime and those operations are pretty cheap. The language doesn't support manual management of goroutines. Switching costs When a thread blocks another has to be scheduled in its place. Threads are scheduled preemptively, and during a thread switch, the scheduler needs to save/restore ALL registers, that is, 16 general purpose registers, PC (Program Counter), SP (Stack Pointer), segment registers, 16 XMM registers, FP coprocessor state, 16 AVX registers, all MSRs etc. This is quite significant when there is rapid switching between threads. Goroutines are scheduled cooperatively and when a switch occurs, only 3 registers need to be saved/restored - Program Counter, Stack Pointer and DX. The cost is much lower. How goroutines are executed As mentioned earlier, the runtime manages the goroutines throughout from creation to scheduling to teardown. The runtime is allocated a few threads on which all the goroutines are multiplexed. At any point of time, each thread will be executing one goroutine. If that goroutine is blocked, then it will be swapped out for another goroutine that will execute on that thread instead.[6]
  • #27 http://blog.nindalf.com/how-goroutines-work/
  • #29 http://divan.github.io/posts/go_concurrency_visualize/
  • #31 Any Questions? https://talks.golang.org/2012/waza.slide#22