SlideShare a Scribd company logo
1 of 105
Download to read offline
Introduction to Programming in Go
Amr Hassan
Apologies
This might feel very rudimentary to you.
But this is an "introduction" after all.
In the beginning... Go was created by those guys
Original intentions
Go has always been intended as a systems programming language (way at the bottom of the application
development stack).
In systems programming you would usually use C/C++ or Python if performance is not an issue for you as
productivity is.
Original intentions
Born out of mutual hatred towards writing and compiling C++ code.
To the surprise of the creators, Go has seen a much higher rate adoption from the scripting crowd
(Python and Ruby), and most of the C/C++ people perceived the simplicity of the langauge as a step back.
Where it is now
Seemingly everywhere
Go is 5 years old now.
To the surprise of its creators, it has grown tremendously in popularity.
It's the new go-to platform for building cloud infrastructure.
Where it is now
List of Go users(https://github.com/golang/go/wiki/GoUsers)
What Go isn't
What Go isn't
Let's start by dialing down your expectations to a manageable level.
Go isn't a functional programming langauge
Although functions are first class objects
Go's adopted style is imperative through and through (sort of like C).
Your code is executed for its side effects, and you reason about your logic as sequential commands
executed to mutate some value within your scope of action.
Purely functional idioms in Go are really counter-productive.
So if you're a functional programming hipster, get over it.
Go isn't an object-oriented language
Although Go has objects.. with methods
And a limited way of doing inheritance (it's actually called composition)
It's not OOP-driven, and won't scratch your pure OOP itch.
Trying to construct rich type hierarchies like in Java or Python is very counter-productive.
Go isn't a high-level language
You might think that's implicit with "systems language", but it isn't. (cough) (Rust) (cough)
Go favors readability above all.
Go Offers just enough syntactic sugar to be productive, but not too much.
That is why a lot of the times verbosity and code simplicity are favored over complex succinctness.
What Go is
What Go is
Hopefully I haven't lost you yet.
Go is Compiled
Compiles to native hardware instructions that can run on the bear metal.
No overhead of a VM or an interpreter.
Comes at the price of doing cross-compilation when you need multiple OS support.
Don't worry, most of the stdlib is cross-compatible.
Go executables are statically-linked
Storage is cheap!
External dependencies and shared binaries are not worth the effort.
Go executables are statically-linked
Very attractive feature right now.
Go is statically-typed (awesomeness)
As you may know, I’m a bit biased towards static typing.
I just think it’s a really neat idea as it makes my life a lot easier.
Go is statically-typed
What is static typing anyway?
Unfortunately static typing has always had this stigma of it being too verbose.
This is not the case anymore in modern languages like Go, because of type inference.
So you kind of get the best of both worlds there.
Go is memory-managed
Go runtime is responsible for allocating memory for your objects.
You never need to worry about the correct (or incorrect) number of bytes to allocate.
Heap, stack or data segments are all fine with you.
Go is memory-managed
Go has a tracing garbage collector.
You never need to worry about who will deallocate your memory when.
You just use objects, pass them around and then stop using them.
Go is memory-managed
Unlike many other memory-managed programming languges, Go has memory pointers.
But since pointer arithmetic is unallowed (easily), it's considered safe.
Go is pragmatic
Built by software engineers (not academics) out of specific programming use cases, not in a "lab" or by
language designers.
Covers most of the areas that the creators felt needed addressing in their day-to-day programming
dendeavours.
Go is minimalistic
Small set of orthogonal features that provide a a sweet spot balance between programmer productivity
and simple software design.
Implies:
- Gentle learning curve
- Human-readable source code
It’s very common for people to pick up the language in an afternoon and start building things
immediately
Huge plus!
Go is modern
As a fairly-new language, the stdlibs come with packages for doing many of the essential jobs that a
programmer in this day would most likely require in her job.
Integrated web development stack and testing tools in the std libs and toolachain.
So no excuse to not be test-driven!
Go is concurrent
Dubbed a "concurrent language" because of support for native building blocks of concurrency built into
the syntax
Go's concurrency building blocks allow you to
- write and execute code concurrently directly from the language syntax
- establish managed (and safe) ways for communicating between concurrently executing code
Go is concurrent
The Go runtime will multiplex your concurrent code for you on actual OS threads, free of charge.
Go is a bit frustrating at first
First impressions of Go is that it's very lacking.
Go is almost never anyone’s first programming language, so everyone comes to it with expectations and
biases about how things should be done according to their system of belief and the kind of programming
idiom they are used to.
Since that Go was built out of frustration with the current state of things, it's meant to disrupt the way you
program.
Go is a bit frustrating at first
You shouldn't give into that initial frustration.
Because it gets rewarding very quickly.
Syntax
Syntax
Most of these examples are derived from the official tour of Go on golang.org.
So if they seem too familiar, that’s probably the reason.
Syntax: Hello World
Execution starts in the main() in the "main" package.
UTF-8 source code files. No special headers. No literal escaping.
You can even declare unicode symbols.
Ω(DoSomething()).Should(Equal("foo"))
You probably shouldn't do that. Nice to know that you can though.
"fmt" is where you find string formatting functions.
"fmt" name is Rob Pike's doing.
package main
import "fmt"
func main() {
fmt.Println("Hello, ‫ﻳﺎ‬‫ﺑﺸﺮ‬ ")
} Run
Syntax: Variables
Variables can be declared in function scope of package scope.
package main
import "fmt"
var c, python, java bool
func main() {
var i int
fmt.Println(i, c, python, java)
} Run
Syntax: Variables with initializers
Type inference in action!
package main
import "fmt"
var i, j int = 1, 2
func main() {
var c, python, java = true, false, "no!"
fmt.Println(i, j, c, python, java)
} Run
Syntax: Shorthand variable declaration
Only inside a function body.
Both declarations are identical.
package main
import "fmt"
func main() {
var i, j int = 1, 2
k := 3
c, python, java := true, false, "no!"
fmt.Println(i, j, k, c, python, java)
} Run
Syntax: Primitive types
bool
string
int int8 int16 int32 int64
uint uint8 uint16 uint32 uint64 uintptr
float32 float64
complex64 complex128
and
byte // alias for uint8
rune // alias for int32 and it represents a Unicode code point
Zero values for booleans is false and for numerical types an actual 0.
Syntax: Primitive types in action
package main
import (
"fmt"
"math/cmplx"
)
var (
ToBe bool = false
MaxInt uint64 = 1<<64 - 1
z complex128 = cmplx.Sqrt(-5 + 12i)
)
func main() {
const f = "%T(%v)n"
fmt.Printf(f, ToBe, ToBe)
fmt.Printf(f, MaxInt, MaxInt)
fmt.Printf(f, z, z)
} Run
Syntax: Type Conversion
Unlike in a lot of other languages where automatic conversion to types with wider percision is allowed,
type conversions in Go must be explicit.
The expression T(v) converts the value v to the type T.
package main
import (
"fmt"
"math"
)
func main() {
var x, y int = 3, 4
var f float64 = math.Sqrt(float64(x*x + y*y))
var z int = int(f)
fmt.Println(x, y, z)
} Run
Syntax: Loops
Syntax: Loops
Your for-s, foreach-es, and your while-s.
Syntax: Loops - For Loop
Very C.
Parens are not allowed. Not even optional!
Body brakcets are obligatory.
package main
import "fmt"
func main() {
sum := 0
for i := 0; i < 10; i++ {
sum += i
}
fmt.Println(sum)
} Run
Syntax: Loops - For Loop
package main
import "fmt"
func main() {
sum := 1
for ; sum < 1000; {
sum += sum
}
fmt.Println(sum)
} Run
Syntax: Loops - While Loop
package main
import "fmt"
func main() {
sum := 1
for sum < 1000 {
sum += sum
}
fmt.Println(sum)
} Run
Syntax: While (TRUE) Loop
package main
import (
"fmt"
"time"
)
func main() {
for {
fmt.Println("Tick!")
time.Sleep(1000)
fmt.Println("Tock!")
time.Sleep(1000)
}
} Run
Syntax: Conditionals - If
Also very C.
Also body brakcets are obligatory
Again, parens are not even optional.
package main
import (
"fmt"
"math"
)
func sqrt(x float64) string {
if x < 0 {
return sqrt(-x) + "i"
}
return fmt.Sprint(math.Sqrt(x))
}
func main() {
fmt.Println(sqrt(2), sqrt(-4))
} Run
Syntax: Conditionals - If with pre-statement
package main
import (
"fmt"
"math"
)
func pow(x, n, lim float64) float64 {
if v := math.Pow(x, n); v < lim {
return v
}
return lim
}
func main() {
fmt.Println(
pow(3, 2, 10),
pow(3, 3, 20),
)
} Run
Syntax: Conditionals - If/else
package main
import (
"fmt"
"math"
)
func pow(x, n, lim float64) float64 {
if v := math.Pow(x, n); v < lim {
return v
} else {
fmt.Printf("%g >= %gn", v, lim)
}
// can't use v here, though
return lim
}
func main() {
fmt.Println(
pow(3, 2, 10),
pow(3, 3, 20),
)
} Run
Syntax: Conditionals - Switch
Switch is a fancy if with multiple if/else clauses.
package main
import (
"fmt"
"runtime"
)
func main() {
fmt.Print("Go runs on ")
switch os := runtime.GOOS; os {
case "darwin":
fmt.Println("OS X.")
case "linux":
fmt.Println("Linux.")
default:
// freebsd, openbsd,
// plan9, windows...
fmt.Printf("%s.", os)
}
} Run
Syntax: Conditionals - Switch case evaluation
switch i {
case 0:
case f():
}
The evaluation order of the switch case statements happens from top to bottom.
Syntax: Functions
The main building block in Go.
You can create nested closures using the func keyword.
package main
import "fmt"
func add(a int, b int) int {
return a + b
}
func main() {
sum := add(3, 1)
fmt.Println("Initial sum", sum)
// Closures! and first-class function values
incrementSum := func() { sum += 1 }
incrementSum()
incrementSum()
fmt.Println("Incremented sum", sum)
} Run
Syntax: Functions
The type of function values is:
func([argument_list]) [return_type]
Syntax: Higher order functions
We can use function types to declare some higher order functions like
package main
import "fmt"
func add(a int, b int) int { return a + b }
func subtract(a, b int) int { return a - b }
func execute(a, b int, operation func(int, int) int) int { // shorthand for duplicate types
return operation(a, b)
}
func main() {
i, j := 4, 2
added := execute(i, j, add)
fmt.Printf("Added %d + %d == %dn", i, j, added)
subtracted := execute(i, j, subtract)
fmt.Printf("Subtracted %d - %d == %dn", i, j, subtracted)
} Run
Syntax: Defer
An awesome Go-first!
Push clean-up code to be executed before the function returns in LIFO.
Go's way of making up for not managing resources for you other than memory and CPU.
package main
import "fmt"
func main() {
defer fmt.Println("world")
fmt.Println("hello")
} Run
Syntax: Stacking defer statements
package main
import "fmt"
func main() {
fmt.Println("counting")
for i := 0; i < 10; i++ {
defer fmt.Println(i)
}
fmt.Println("done")
} Run
Syntax: Pointers
A Go pointer value is nothing but a typed memory addresses, much like a C pointer.
*T is a pointer to a T value
The zero value of a pointer is nil (no garbage values in Go).
Syntax: Pointers
This is how you declare a pointer.
var p *int
The & operator generates a pointer to its operand.
i := 42
p = &i
The * operator denotes the pointer's underlying value.
fmt.Println(*p) // read i through the pointer p
Dereferencing a pointer is also via the * operator.
*p = 21 // set i through the pointer p
Unlike C, Go has no pointer arithmetic.
Syntax: Structs
The the way of building heterogeneous aggregate custom types in Go.
That's fancy talk for saying it's a collection of fields of different types.
package main
import "fmt"
type Vertex struct {
X int
Y int
}
func main() {
fmt.Println(Vertex{1, 2})
} Run
Syntax: Structs
Struct fields are accessible using the dot notation
package main
import "fmt"
type Vertex struct {
X int
Y int
}
func main() {
v := Vertex{1, 2}
v.X = 4
fmt.Println(v.X)
} Run
Syntax: Struct literal notation
package main
import "fmt"
type Vertex struct {
X, Y int
}
var (
v1 = Vertex{1, 2} // has type Vertex
v2 = Vertex{X: 1} // Y:0 is implicit
v3 = Vertex{} // X:0 and Y:0
p = &Vertex{1, 2} // has type *Vertex
)
func main() {
fmt.Println(v1, p, v2, v3)
} Run
Syntax: Pointers to structs
Quickly instantiate and populate with values a struct all at once
package main
import "fmt"
type Vertex struct {
X int
Y int
}
func main() {
v := Vertex{1, 2}
p := &v
p.X = 1e9
fmt.Println(v)
} Run
Syntax: Structs are your main objects
If you’re coming from a strictly OOP language like Java, the only thing you would be thinking about in your
program design, is classes.
Classes this, classes that, classes everywhere.
Syntax: Structs are your main objects
Go creators did not like that approach where everything had to be a class.
Sometimes, the simplest most correct way to express your computation, is just as a function.
Go fell back to the minimalistic approach of C, where your data structures are just pure aggregate data.
And you can as an added bonus, you can specify type-specific operations on each of your custom types.
It’s like how in C you would declare struct s and then declare functions that all accept a pointer to the
struct as their first argument by convention.
Syntax: Struct methods
Two argument lists. First one only has the "receiver" argument. Second one has zero or more argumetns
of your method.
Dot notation for invoking struct methods on the receiver.
package main
import ("fmt"; "math")
type Vector struct {
X float64
Y float64
}
func (v Vector) Magnitude() float64 { return math.Sqrt(v.X*v.X + v.Y*v.Y) }
func (v *Vector) Add(other *Vector) *Vector { return &Vector{X: v.X + other.X, Y: v.Y + other.Y} }
func main() {
vec := Vector{3.0, 4.0}
fmt.Println(vec)
fmt.Println(vec.Magnitude())
fmt.Println(vec.Add(&Vector{6.0, 4.0}))
} Run
Syntax: Arrays
The way of constructing homogeneous aggregate types in Go (a sequence of values of the same type).
Analogous to boring C arrays.
Fixed in size.
Size is part of the type.
package main
import "fmt"
func main() {
var a [2]string
a[0] = "Hello"
a[1] = "World"
fmt.Println(a[0], a[1])
fmt.Println(a)
} Run
Syntax: Slices
Slices are arrays on steroids.
Go makes up for the fact that it doesn’t let you do pointer arithmetic, by giving you this much cooler and
easier to use concept of slices.
A slice is more or less a view into a subset of an array.
[]T is a slice with elements of type T.
A slice's size is not reflected in its type.
Syntax: Slices
The slice literal notation lets you create slices backed by anonymous arrays very easily and populate them
with values on the spot.
Slices are used just like you would use an array, except for a couple of extra very neat features.
package main
import "fmt"
func main() {
p := []int{2, 3, 5, 7, 11, 13}
fmt.Println("p ==", p)
for i := 0; i < len(p); i++ {
fmt.Printf("p[%d] == %dn", i, p[i])
}
} Run
Syntax: Slicing slices
You can slice slices!
Very similar to sequence slicing in Python (except that negative indices are not supported).
You can slice into a slice to get a new view into its backing array, or you can slice into an already existing
array to get a slice from that.
package main
import "fmt"
func main() {
p := []int{2, 3, 5, 7, 11, 13}
fmt.Println("p ==", p)
fmt.Println("p[1:4] ==", p[1:4])
// missing low index implies 0
fmt.Println("p[:3] ==", p[:3])
// missing high index implies len(s)
fmt.Println("p[4:] ==", p[4:])
} Run
Syntax: Slicing slices
The zero value of a slice is nil.
Syntax: Appending to slices
package main
import "fmt"
func main() {
var a []int
printSlice("a", a)
// append works on nil slices.
a = append(a, 0)
printSlice("a", a)
// the slice grows as needed.
a = append(a, 1)
printSlice("a", a)
// we can add more than one element at a time.
a = append(a, 2, 3, 4)
printSlice("a", a)
}
func printSlice(s string, x []int) {
fmt.Printf("%s len=%d cap=%d %vn",
s, len(x), cap(x), x)
} Run
Syntax: Appending to slices
If the backing array of the slice is too short, then append() would create a new backing array big enough
and use that in the returned slice.
Syntax: Maps
The native type-safe associative array in Go is the hash map, almost identical to the native map type in
Python.
Syntax: Maps
You must create a map using the make() function before usage, because the zero value of map is nil and
using that as a map causes in an error.
You can create maps from any type to any type.
package main
import "fmt"
type Vertex struct {
Lat, Long float64
}
var m map[string]Vertex
func main() {
m = make(map[string]Vertex)
m["Bell Labs"] = Vertex{
40.68433, -74.39967,
}
fmt.Println(m["Bell Labs"])
} Run
Syntax: Map Literals
package main
import "fmt"
type Vertex struct {
Lat, Long float64
}
var m = map[string]Vertex{
"Bell Labs": Vertex{
40.68433, -74.39967,
},
"Google": Vertex{
37.42202, -122.08408,
},
}
func main() {
fmt.Println(m)
} Run
Syntax: Map operations
package main
import "fmt"
func main() {
m := make(map[string]int)
m["Answer"] = 42
fmt.Println("The value:", m["Answer"])
m["Answer"] = 48
fmt.Println("The value:", m["Answer"])
delete(m, "Answer")
fmt.Println("The value:", m["Answer"])
v, exists := m["Answer"]
fmt.Println("The value:", v, "Present?", exists)
} Run
Syntax: Range loops
21st century looping in Go
Similar to Python sequence looping
for i, v in enumerate([1, 2, 3])
and map looping
for k, v in mapping.items()
package main
import "fmt"
var pow = []int{1, 2, 4, 8, 16, 32, 64, 128}
func main() {
for i, v := range pow {
fmt.Printf("2**%d = %dn", i, v)
}
} Run
The Zen of Go
The Zen of Go: Interfaces
Go resists this:
- subtype polymorphism (inheritance).
- parametric-type polymorphism (generics).
It instead emphasizes polymorphism via interfaces.
The Zen of Go: Interfaces
Go interfaces are small.
type Stringer interface {
String() string
}
A Stringer can pretty print itself.
Anything that implements String is a Stringer.
Interfaces are implemented implicitly.
The Zen of Go: Interfaces
Interfaces are types.
package main
import "fmt"
type Named interface {
Name() string
}
func greet(someone Named) { fmt.Println("Greetings, " + someone.Name()) }
type Human struct {
firstName string
}
func (h Human) Name() string {
return h.firstName
}
func main() {
greet(Human{firstName: "Jack Bauer"})
} Run
The Zen of Go: Interfaces
A Sorting example
package main
import ("fmt"; "sort")
type Person struct {
Name string
Age int
}
func (p Person) String() string { return fmt.Sprintf("%s: %d", p.Name, p.Age) }
// ByAge implements sort.Interface for []Person based on
// the Age field.
type ByAge []Person
func (a ByAge) Len() int { return len(a) }
func (a ByAge) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func (a ByAge) Less(i, j int) bool { return a[i].Age < a[j].Age }
func main() {
people := []Person{{"Bob", 31}, {"John", 42}, {"Michael", 17}, {"Jenny", 26}}
fmt.Println(people)
sort.Sort(ByAge(people))
fmt.Println(people)
} Run
The Zen of Go: Error handling
The Zen of Go: Error handling
Unchecked exceptions are evil.
This is not scripting. You're building "robust" infrastructure software.
"Let it crash" cannot be the default way of handling errors.
Every computation that can fail must be executed with proper "error handling code".
The Zen of Go: Error handling
Memorize this pattern. You're gonna use it so much it'll haunt you in your dreams.
package main
import (
"fmt"
)
func getMyText() (string, error) {
// This could have been read from disk or a network socket
return "Your text", nil
}
func main() {
myText, err := getMyText()
if err != nil {
myText = "Sorry, I couldn't get your text. May I interest you in a joke?"
}
fmt.Println(myText)
} Run
The Zen of Go: Error handling
Go chose simplest approach possible to error handling.
Errors are plain regular values that implement the error interface.
type error {
Error() string
}
You should either handle an error or propagate it upwards.
The Zen of Go: Error handling
Unexpected errors should not be expected
package main
import ("fmt"; "regexp")
func extractLongestNumber(text string) string {
extractorRegexp, err := regexp.Compile("([0-9]+)")
if err != nil {
panic(err) // This will crash with a stack trace and the value of err
}
matches := extractorRegexp.FindStringSubmatch(text)
if len(matches) > 1 { return matches[1] } else { return "" }
}
func main() {
myText := "Sonmi-451"
fmt.Println(extractLongestNumber(myText))
} Run
The Zen of Go: Error handling
This is so common that there's a pattern for it.
package main
import ("fmt"; "regexp")
func extractLongestNumber(text string) string {
extractorRegexp := regexp.MustCompile("([0-9]+)")
matches := extractorRegexp.FindStringSubmatch(text)
if len(matches) > 1 { return matches[1] } else { return "" }
}
func main() {
myText := "Sonmi-451"
fmt.Println(extractLongestNumber(myText))
} Run
The Zen of Go: Error handling
Having to handle every each possible error case manually is a common first-day complaint in Go
You get used to it very quickly.
You will definitely feel its reward when you run your code and find it correct and not crashing the first
time.
The Zen of Go: Packages
The Zen of Go: Packages
Packages are one more thing that newcomers clash against.
Go comes with its own way of doing packages and file hierarchy for source code.
Just stop fighting it.
The Zen of Go: Packages
The first thing you'll do after installing the Go SDK is setting up your $GOPATH.
$GOPATH is structured like so:
|- src
|- bin
|- pkg
The import path of your packages is going to be the relative path under your $GOPATH/src directory.
Doing
import "coderize/awesomelib"
imports the package from $GOPATH/src/coderize/awesomelib as the awesomelib package
It's as simple as that. Don't invent your own system.
The Zen of Go: Visibility
Code visibility is only on the package level.
Only symbols starting with an upper class letter are exported.
package awesomelib
type ExportedType interface {
PublicAction()
}
type internalType struct {
internalNumber int
}
func (a internalType) PublicAction() { /* I work in silence*/ }
func internalDityWork() { /* TMI*/ }
func NewAwesomeness() ExportedType { /* TMI*/ return internalType{internalNumber: 42} }
The Zen of Go: Documentation
The Zen of Go: Documentation
No special syntax.
Code documentation should be readable to humans in source code text format.
// Accepts an io.Reader and does the agreed-upon computation and returns the result
// or a descriptive error if something went wrong.
func ExportedFunction(reader io.Reader) (Result, error)
No special markup tags to describe parameters or return types.
If you make sure all your exported symbols are documented, Godoc can render that into perfectly
presentable HTML for you.
godoc(http://godoc.org/)
The Zen of Go: Concurrency
The Zen of Go: Concurrency
I've saved the best for last.
Concurrency is a session topic on its own.
Let's just skim over of what Go has to offer.
The Zen of Go: Concurrency
A goroutine is a lightweight thread managed by the Go runtime.
Go routines are multiplexed over multiple actual OS threads by the runtime.
go f(x, y, z)
starts a new goroutine running
f(x, y, z)
The Zen of Go: Concurrency
package main
import (
"fmt"
"time"
)
func say(s string) {
for i := 0; i < 5; i++ {
time.Sleep(100 * time.Millisecond)
fmt.Println(s)
}
}
func main() {
go say("world")
say("hello")
} Run
The Zen of Go: Concurrency
A channel is a typed synchronized queue.
boolChannel := make(chan bool) // I created a boolean channel of type "chan bool"
Channels are utilized for communication and synchronization between running goroutines.
There are three things you can do on a channel: send stuff, receive stuff, or close the channel.
boolChan <- = false
boolChan <- = true
boolChan <- = true
close(boolChan)
I just sent a "false" and two "true"s to the channel then closed it.
The Zen of Go: Concurrency
On the receiving end:
// Listens on the given channel for three incoming boolean messages and returns true if any one
// was true
func getMyBooleans(myChannel chan bool) bool {
firstMessage, isOpen := <- boolChan
if !isOpen {
return false
}
secondMessage, isOpen := <- boolChan
if !isOpen {
return firstMessage
}
thirdMessage, isOpen := <- boolChan
if !isOpen {
return firstMessage | secondMessage
}
return firstMessage | secondMessage | thirdMessage
}
The Zen of Go: Concurrency
Too verbose? range to the rescue:
// Listens on the given channel for incoming boolean messages and returns true if any one
// was true
func getMyBooleans(myChannel chan bool) bool {
message := false
for incomingMessage := myChannel {
message |= incomingMessage
}
return message
}
The Zen of Go: Concurrency
Channel sends and receives are blocking operations. So they're perfect for doing "lock-free"
synchronization.
The Zen of Go: Concurrency
Here's a really dumb example that takes too much time to compute
package main
import "fmt"
func fibonacci(i uint) uint {
if i <= 1 {
return 1
}
return fibonacci(i-1) + fibonacci(i-2)
}
func main() {
fmt.Println(fibonacci(41))
fmt.Println(fibonacci(41))
} Run
The Zen of Go: Concurrency
Same example but now made faster using parallelism via goroutines and channels.
package main
import "fmt"
func compute(computation func() int) <- chan int {
outputChannel := make(chan int)
go func() {
outputChannel <- computation()
}()
return outputChannel
}
func fibonacci(i int) int { if i <= 1 { return 1 } else {return fibonacci(i-1) + fibonacci(i-2) }}
func main() {
computation := func() int {return fibonacci(41)}
firstResult := compute(computation)
secondResult := compute(computation)
// Now I'm gonna block and wait for the two results
fmt.Println(<- firstResult)
fmt.Println(<- secondResult)
} Run
Where to Go from here (pun intended)
Where to Go from here (pun intended)
There are still several things that I did not have the time to cover in Go.
I suggest checking out the links below.
Take the Go tour yourself(http://tour.golang.org/)
Go for Gophers (by Andrew Gerrand)(https://talks.golang.org/2014/go4gophers.slide)
Go Concurrency Patterns (by the awesome Rob Pike)(https://www.youtube.com/watch?feature=player_detailpage&v=f6kdp27TYZs)
Go subreddit(http://www.reddit.com/r/golang)
Thank you
Amr Hassan

More Related Content

What's hot

Introduction to go language programming
Introduction to go language programmingIntroduction to go language programming
Introduction to go language programmingMahmoud Masih Tehrani
 
7 Common mistakes in Go and when to avoid them
7 Common mistakes in Go and when to avoid them7 Common mistakes in Go and when to avoid them
7 Common mistakes in Go and when to avoid themSteven Francia
 
Programming with Python - Basic
Programming with Python - BasicProgramming with Python - Basic
Programming with Python - BasicMosky Liu
 
Golang iran - tutorial go programming language - Preliminary
Golang iran - tutorial  go programming language - PreliminaryGolang iran - tutorial  go programming language - Preliminary
Golang iran - tutorial go programming language - Preliminarygo-lang
 
Vim Script Programming
Vim Script ProgrammingVim Script Programming
Vim Script ProgrammingLin Yo-An
 
EuroPython 2016 - Do I Need To Switch To Golang
EuroPython 2016 - Do I Need To Switch To GolangEuroPython 2016 - Do I Need To Switch To Golang
EuroPython 2016 - Do I Need To Switch To GolangMax Tepkeev
 
PyCon 2013 : Scripting to PyPi to GitHub and More
PyCon 2013 : Scripting to PyPi to GitHub and MorePyCon 2013 : Scripting to PyPi to GitHub and More
PyCon 2013 : Scripting to PyPi to GitHub and MoreMatt Harrison
 
Why Python (for Statisticians)
Why Python (for Statisticians)Why Python (for Statisticians)
Why Python (for Statisticians)Matt Harrison
 
GO programming language
GO programming languageGO programming language
GO programming languagetung vu
 
pyconjp2015_talk_Translation of Python Program__
pyconjp2015_talk_Translation of Python Program__pyconjp2015_talk_Translation of Python Program__
pyconjp2015_talk_Translation of Python Program__Renyuan Lyu
 
Learning Python from Data
Learning Python from DataLearning Python from Data
Learning Python from DataMosky Liu
 
Introduction to Go language
Introduction to Go languageIntroduction to Go language
Introduction to Go languageTzar Umang
 
Writing Fast Code (JP) - PyCon JP 2015
Writing Fast Code (JP) - PyCon JP 2015Writing Fast Code (JP) - PyCon JP 2015
Writing Fast Code (JP) - PyCon JP 2015Younggun Kim
 
Programming with Python - Adv.
Programming with Python - Adv.Programming with Python - Adv.
Programming with Python - Adv.Mosky Liu
 
Presentation of Python, Django, DockerStack
Presentation of Python, Django, DockerStackPresentation of Python, Django, DockerStack
Presentation of Python, Django, DockerStackDavid Sanchez
 
2016 bioinformatics i_python_part_2_strings_wim_vancriekinge
2016 bioinformatics i_python_part_2_strings_wim_vancriekinge2016 bioinformatics i_python_part_2_strings_wim_vancriekinge
2016 bioinformatics i_python_part_2_strings_wim_vancriekingeProf. Wim Van Criekinge
 
Open source projects with python
Open source projects with pythonOpen source projects with python
Open source projects with pythonroskakori
 
What we can learn from Rebol?
What we can learn from Rebol?What we can learn from Rebol?
What we can learn from Rebol?lichtkind
 

What's hot (20)

Introduction to go language programming
Introduction to go language programmingIntroduction to go language programming
Introduction to go language programming
 
7 Common mistakes in Go and when to avoid them
7 Common mistakes in Go and when to avoid them7 Common mistakes in Go and when to avoid them
7 Common mistakes in Go and when to avoid them
 
Programming with Python - Basic
Programming with Python - BasicProgramming with Python - Basic
Programming with Python - Basic
 
Golang iran - tutorial go programming language - Preliminary
Golang iran - tutorial  go programming language - PreliminaryGolang iran - tutorial  go programming language - Preliminary
Golang iran - tutorial go programming language - Preliminary
 
Go Lang Tutorial
Go Lang TutorialGo Lang Tutorial
Go Lang Tutorial
 
Vim Script Programming
Vim Script ProgrammingVim Script Programming
Vim Script Programming
 
EuroPython 2016 - Do I Need To Switch To Golang
EuroPython 2016 - Do I Need To Switch To GolangEuroPython 2016 - Do I Need To Switch To Golang
EuroPython 2016 - Do I Need To Switch To Golang
 
PyCon 2013 : Scripting to PyPi to GitHub and More
PyCon 2013 : Scripting to PyPi to GitHub and MorePyCon 2013 : Scripting to PyPi to GitHub and More
PyCon 2013 : Scripting to PyPi to GitHub and More
 
Why Python (for Statisticians)
Why Python (for Statisticians)Why Python (for Statisticians)
Why Python (for Statisticians)
 
Golang
GolangGolang
Golang
 
GO programming language
GO programming languageGO programming language
GO programming language
 
pyconjp2015_talk_Translation of Python Program__
pyconjp2015_talk_Translation of Python Program__pyconjp2015_talk_Translation of Python Program__
pyconjp2015_talk_Translation of Python Program__
 
Learning Python from Data
Learning Python from DataLearning Python from Data
Learning Python from Data
 
Introduction to Go language
Introduction to Go languageIntroduction to Go language
Introduction to Go language
 
Writing Fast Code (JP) - PyCon JP 2015
Writing Fast Code (JP) - PyCon JP 2015Writing Fast Code (JP) - PyCon JP 2015
Writing Fast Code (JP) - PyCon JP 2015
 
Programming with Python - Adv.
Programming with Python - Adv.Programming with Python - Adv.
Programming with Python - Adv.
 
Presentation of Python, Django, DockerStack
Presentation of Python, Django, DockerStackPresentation of Python, Django, DockerStack
Presentation of Python, Django, DockerStack
 
2016 bioinformatics i_python_part_2_strings_wim_vancriekinge
2016 bioinformatics i_python_part_2_strings_wim_vancriekinge2016 bioinformatics i_python_part_2_strings_wim_vancriekinge
2016 bioinformatics i_python_part_2_strings_wim_vancriekinge
 
Open source projects with python
Open source projects with pythonOpen source projects with python
Open source projects with python
 
What we can learn from Rebol?
What we can learn from Rebol?What we can learn from Rebol?
What we can learn from Rebol?
 

Viewers also liked

18 Minute Presentation In Greek
18 Minute Presentation In Greek18 Minute Presentation In Greek
18 Minute Presentation In GreekFred Johansen
 
XestióN Orzamentaria Das SubvencióNs
XestióN Orzamentaria Das SubvencióNsXestióN Orzamentaria Das SubvencióNs
XestióN Orzamentaria Das SubvencióNsMCORGOS
 
Vevdronningen offentlig virksomhet i sosiale medier, bare enkelt
Vevdronningen offentlig virksomhet i sosiale medier, bare enkeltVevdronningen offentlig virksomhet i sosiale medier, bare enkelt
Vevdronningen offentlig virksomhet i sosiale medier, bare enkeltIngeborg Dirdal
 
Introduksjon til GIS
Introduksjon til GISIntroduksjon til GIS
Introduksjon til GISFred Johansen
 
The future will be Realtime & Collaborative
The future will be Realtime & CollaborativeThe future will be Realtime & Collaborative
The future will be Realtime & CollaborativeJoseph Gentle
 
molson coors brewing COORS_AR1998
molson coors brewing  COORS_AR1998molson coors brewing  COORS_AR1998
molson coors brewing COORS_AR1998finance46
 
Thesis110309
Thesis110309Thesis110309
Thesis110309klee4vp
 
ZnO基稀磁半导体共掺杂体系
ZnO基稀磁半导体共掺杂体系ZnO基稀磁半导体共掺杂体系
ZnO基稀磁半导体共掺杂体系cscguochang
 
MAKE-UP interattiviamoci_gruppo2
MAKE-UP interattiviamoci_gruppo2MAKE-UP interattiviamoci_gruppo2
MAKE-UP interattiviamoci_gruppo2silvia_ruggeri
 
Thesis100609
Thesis100609Thesis100609
Thesis100609klee4vp
 
tenneco annual reports 2004
tenneco annual reports 2004tenneco annual reports 2004
tenneco annual reports 2004finance46
 
omnicare annual reports 1994
omnicare annual reports 1994omnicare annual reports 1994
omnicare annual reports 1994finance46
 
How to Structure a Blog Post to Create More Leads [V2]
How to Structure a Blog Post to Create More Leads [V2]How to Structure a Blog Post to Create More Leads [V2]
How to Structure a Blog Post to Create More Leads [V2]Mariana Wagner
 
autozone g64620ars
autozone  g64620ars autozone  g64620ars
autozone g64620ars finance46
 

Viewers also liked (20)

18 Minute Presentation In Greek
18 Minute Presentation In Greek18 Minute Presentation In Greek
18 Minute Presentation In Greek
 
XestióN Orzamentaria Das SubvencióNs
XestióN Orzamentaria Das SubvencióNsXestióN Orzamentaria Das SubvencióNs
XestióN Orzamentaria Das SubvencióNs
 
Vevdronningen offentlig virksomhet i sosiale medier, bare enkelt
Vevdronningen offentlig virksomhet i sosiale medier, bare enkeltVevdronningen offentlig virksomhet i sosiale medier, bare enkelt
Vevdronningen offentlig virksomhet i sosiale medier, bare enkelt
 
Maximo Overview
Maximo OverviewMaximo Overview
Maximo Overview
 
Introduksjon til GIS
Introduksjon til GISIntroduksjon til GIS
Introduksjon til GIS
 
Seo010610
Seo010610Seo010610
Seo010610
 
The future will be Realtime & Collaborative
The future will be Realtime & CollaborativeThe future will be Realtime & Collaborative
The future will be Realtime & Collaborative
 
Educational Podcasting
Educational PodcastingEducational Podcasting
Educational Podcasting
 
molson coors brewing COORS_AR1998
molson coors brewing  COORS_AR1998molson coors brewing  COORS_AR1998
molson coors brewing COORS_AR1998
 
Thesis110309
Thesis110309Thesis110309
Thesis110309
 
ZnO基稀磁半导体共掺杂体系
ZnO基稀磁半导体共掺杂体系ZnO基稀磁半导体共掺杂体系
ZnO基稀磁半导体共掺杂体系
 
MAKE-UP interattiviamoci_gruppo2
MAKE-UP interattiviamoci_gruppo2MAKE-UP interattiviamoci_gruppo2
MAKE-UP interattiviamoci_gruppo2
 
Thesis100609
Thesis100609Thesis100609
Thesis100609
 
tenneco annual reports 2004
tenneco annual reports 2004tenneco annual reports 2004
tenneco annual reports 2004
 
omnicare annual reports 1994
omnicare annual reports 1994omnicare annual reports 1994
omnicare annual reports 1994
 
The Piece Of Cake
The Piece Of CakeThe Piece Of Cake
The Piece Of Cake
 
How to Structure a Blog Post to Create More Leads [V2]
How to Structure a Blog Post to Create More Leads [V2]How to Structure a Blog Post to Create More Leads [V2]
How to Structure a Blog Post to Create More Leads [V2]
 
Les Cultures
Les CulturesLes Cultures
Les Cultures
 
autozone g64620ars
autozone  g64620ars autozone  g64620ars
autozone g64620ars
 
Twitter: For Beginners
Twitter: For BeginnersTwitter: For Beginners
Twitter: For Beginners
 

Similar to Introduction to Programming in Go

Go language presentation
Go language presentationGo language presentation
Go language presentationparamisoft
 
Introduction to Google's Go programming language
Introduction to Google's Go programming languageIntroduction to Google's Go programming language
Introduction to Google's Go programming languageMario Castro Contreras
 
Python intro
Python introPython intro
Python introrik0
 
Programming Under Linux In Python
Programming Under Linux In PythonProgramming Under Linux In Python
Programming Under Linux In PythonMarwan Osman
 
Let's Go: Introduction to Google's Go Programming Language
Let's Go: Introduction to Google's Go Programming LanguageLet's Go: Introduction to Google's Go Programming Language
Let's Go: Introduction to Google's Go Programming LanguageGanesh Samarthyam
 
Lets Go - An introduction to Google's Go Programming Language
Lets Go - An introduction to Google's Go Programming Language Lets Go - An introduction to Google's Go Programming Language
Lets Go - An introduction to Google's Go Programming Language Ganesh Samarthyam
 
OSCON2014 : Quick Introduction to System Tools Programming with Go
OSCON2014 : Quick Introduction to System Tools Programming with GoOSCON2014 : Quick Introduction to System Tools Programming with Go
OSCON2014 : Quick Introduction to System Tools Programming with GoChris McEniry
 
The Ring programming language version 1.7 book - Part 89 of 196
The Ring programming language version 1.7 book - Part 89 of 196The Ring programming language version 1.7 book - Part 89 of 196
The Ring programming language version 1.7 book - Part 89 of 196Mahmoud Samir Fayed
 
Which is better, Java or Python? And how?
Which is better, Java or Python? And how?Which is better, Java or Python? And how?
Which is better, Java or Python? And how?narendrachinnu
 
Google's Go Programming Language - Introduction
Google's Go Programming Language - Introduction Google's Go Programming Language - Introduction
Google's Go Programming Language - Introduction Ganesh Samarthyam
 
A First Look at Google's Go Programming Language
A First Look at Google's Go Programming LanguageA First Look at Google's Go Programming Language
A First Look at Google's Go Programming LanguageGanesh Samarthyam
 
Golang basics for Java developers - Part 1
Golang basics for Java developers - Part 1Golang basics for Java developers - Part 1
Golang basics for Java developers - Part 1Robert Stern
 
ooc - A hybrid language experiment
ooc - A hybrid language experimentooc - A hybrid language experiment
ooc - A hybrid language experimentAmos Wenger
 
ooc - A hybrid language experiment
ooc - A hybrid language experimentooc - A hybrid language experiment
ooc - A hybrid language experimentAmos Wenger
 
Golang - Overview of Go (golang) Language
Golang - Overview of Go (golang) LanguageGolang - Overview of Go (golang) Language
Golang - Overview of Go (golang) LanguageAniruddha Chakrabarti
 
10 reasons to be excited about go
10 reasons to be excited about go10 reasons to be excited about go
10 reasons to be excited about goDvir Volk
 
The GO Language : From Beginners to Gophers
The GO Language : From Beginners to GophersThe GO Language : From Beginners to Gophers
The GO Language : From Beginners to GophersAlessandro Sanino
 

Similar to Introduction to Programming in Go (20)

Beginning development in go
Beginning development in goBeginning development in go
Beginning development in go
 
Go language presentation
Go language presentationGo language presentation
Go language presentation
 
Introduction to Google's Go programming language
Introduction to Google's Go programming languageIntroduction to Google's Go programming language
Introduction to Google's Go programming language
 
Python intro
Python introPython intro
Python intro
 
Programming Under Linux In Python
Programming Under Linux In PythonProgramming Under Linux In Python
Programming Under Linux In Python
 
Let's Go: Introduction to Google's Go Programming Language
Let's Go: Introduction to Google's Go Programming LanguageLet's Go: Introduction to Google's Go Programming Language
Let's Go: Introduction to Google's Go Programming Language
 
Lets Go - An introduction to Google's Go Programming Language
Lets Go - An introduction to Google's Go Programming Language Lets Go - An introduction to Google's Go Programming Language
Lets Go - An introduction to Google's Go Programming Language
 
Pyhton-1a-Basics.pdf
Pyhton-1a-Basics.pdfPyhton-1a-Basics.pdf
Pyhton-1a-Basics.pdf
 
OSCON2014 : Quick Introduction to System Tools Programming with Go
OSCON2014 : Quick Introduction to System Tools Programming with GoOSCON2014 : Quick Introduction to System Tools Programming with Go
OSCON2014 : Quick Introduction to System Tools Programming with Go
 
Golang workshop
Golang workshopGolang workshop
Golang workshop
 
The Ring programming language version 1.7 book - Part 89 of 196
The Ring programming language version 1.7 book - Part 89 of 196The Ring programming language version 1.7 book - Part 89 of 196
The Ring programming language version 1.7 book - Part 89 of 196
 
Which is better, Java or Python? And how?
Which is better, Java or Python? And how?Which is better, Java or Python? And how?
Which is better, Java or Python? And how?
 
Google's Go Programming Language - Introduction
Google's Go Programming Language - Introduction Google's Go Programming Language - Introduction
Google's Go Programming Language - Introduction
 
A First Look at Google's Go Programming Language
A First Look at Google's Go Programming LanguageA First Look at Google's Go Programming Language
A First Look at Google's Go Programming Language
 
Golang basics for Java developers - Part 1
Golang basics for Java developers - Part 1Golang basics for Java developers - Part 1
Golang basics for Java developers - Part 1
 
ooc - A hybrid language experiment
ooc - A hybrid language experimentooc - A hybrid language experiment
ooc - A hybrid language experiment
 
ooc - A hybrid language experiment
ooc - A hybrid language experimentooc - A hybrid language experiment
ooc - A hybrid language experiment
 
Golang - Overview of Go (golang) Language
Golang - Overview of Go (golang) LanguageGolang - Overview of Go (golang) Language
Golang - Overview of Go (golang) Language
 
10 reasons to be excited about go
10 reasons to be excited about go10 reasons to be excited about go
10 reasons to be excited about go
 
The GO Language : From Beginners to Gophers
The GO Language : From Beginners to GophersThe GO Language : From Beginners to Gophers
The GO Language : From Beginners to Gophers
 

Recently uploaded

Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)OPEN KNOWLEDGE GmbH
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsAndolasoft Inc
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Modelsaagamshah0812
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AIABDERRAOUF MEHENNI
 
Active Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdfActive Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdfCionsystems
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfkalichargn70th171
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationkaushalgiri8080
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataBradBedford3
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideChristina Lin
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about usDynamic Netsoft
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfjoe51371421
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerThousandEyes
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxComplianceQuest1
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 

Recently uploaded (20)

Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
 
Active Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdfActive Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdf
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanation
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about us
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdf
 
Exploring iOS App Development: Simplifying the Process
Exploring iOS App Development: Simplifying the ProcessExploring iOS App Development: Simplifying the Process
Exploring iOS App Development: Simplifying the Process
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 

Introduction to Programming in Go

  • 1. Introduction to Programming in Go Amr Hassan
  • 2. Apologies This might feel very rudimentary to you. But this is an "introduction" after all.
  • 3. In the beginning... Go was created by those guys
  • 4. Original intentions Go has always been intended as a systems programming language (way at the bottom of the application development stack). In systems programming you would usually use C/C++ or Python if performance is not an issue for you as productivity is.
  • 5. Original intentions Born out of mutual hatred towards writing and compiling C++ code. To the surprise of the creators, Go has seen a much higher rate adoption from the scripting crowd (Python and Ruby), and most of the C/C++ people perceived the simplicity of the langauge as a step back.
  • 6. Where it is now Seemingly everywhere Go is 5 years old now. To the surprise of its creators, it has grown tremendously in popularity. It's the new go-to platform for building cloud infrastructure.
  • 7. Where it is now List of Go users(https://github.com/golang/go/wiki/GoUsers)
  • 9. What Go isn't Let's start by dialing down your expectations to a manageable level.
  • 10. Go isn't a functional programming langauge Although functions are first class objects Go's adopted style is imperative through and through (sort of like C). Your code is executed for its side effects, and you reason about your logic as sequential commands executed to mutate some value within your scope of action. Purely functional idioms in Go are really counter-productive. So if you're a functional programming hipster, get over it.
  • 11. Go isn't an object-oriented language Although Go has objects.. with methods And a limited way of doing inheritance (it's actually called composition) It's not OOP-driven, and won't scratch your pure OOP itch. Trying to construct rich type hierarchies like in Java or Python is very counter-productive.
  • 12. Go isn't a high-level language You might think that's implicit with "systems language", but it isn't. (cough) (Rust) (cough) Go favors readability above all. Go Offers just enough syntactic sugar to be productive, but not too much. That is why a lot of the times verbosity and code simplicity are favored over complex succinctness.
  • 14. What Go is Hopefully I haven't lost you yet.
  • 15. Go is Compiled Compiles to native hardware instructions that can run on the bear metal. No overhead of a VM or an interpreter. Comes at the price of doing cross-compilation when you need multiple OS support. Don't worry, most of the stdlib is cross-compatible.
  • 16. Go executables are statically-linked Storage is cheap! External dependencies and shared binaries are not worth the effort.
  • 17. Go executables are statically-linked Very attractive feature right now.
  • 18. Go is statically-typed (awesomeness) As you may know, I’m a bit biased towards static typing. I just think it’s a really neat idea as it makes my life a lot easier.
  • 19. Go is statically-typed What is static typing anyway? Unfortunately static typing has always had this stigma of it being too verbose. This is not the case anymore in modern languages like Go, because of type inference. So you kind of get the best of both worlds there.
  • 20. Go is memory-managed Go runtime is responsible for allocating memory for your objects. You never need to worry about the correct (or incorrect) number of bytes to allocate. Heap, stack or data segments are all fine with you.
  • 21. Go is memory-managed Go has a tracing garbage collector. You never need to worry about who will deallocate your memory when. You just use objects, pass them around and then stop using them.
  • 22. Go is memory-managed Unlike many other memory-managed programming languges, Go has memory pointers. But since pointer arithmetic is unallowed (easily), it's considered safe. Go is pragmatic Built by software engineers (not academics) out of specific programming use cases, not in a "lab" or by language designers. Covers most of the areas that the creators felt needed addressing in their day-to-day programming dendeavours.
  • 23. Go is minimalistic Small set of orthogonal features that provide a a sweet spot balance between programmer productivity and simple software design. Implies: - Gentle learning curve - Human-readable source code It’s very common for people to pick up the language in an afternoon and start building things immediately Huge plus!
  • 24. Go is modern As a fairly-new language, the stdlibs come with packages for doing many of the essential jobs that a programmer in this day would most likely require in her job. Integrated web development stack and testing tools in the std libs and toolachain. So no excuse to not be test-driven!
  • 25. Go is concurrent Dubbed a "concurrent language" because of support for native building blocks of concurrency built into the syntax Go's concurrency building blocks allow you to - write and execute code concurrently directly from the language syntax - establish managed (and safe) ways for communicating between concurrently executing code
  • 26. Go is concurrent The Go runtime will multiplex your concurrent code for you on actual OS threads, free of charge.
  • 27. Go is a bit frustrating at first First impressions of Go is that it's very lacking. Go is almost never anyone’s first programming language, so everyone comes to it with expectations and biases about how things should be done according to their system of belief and the kind of programming idiom they are used to. Since that Go was built out of frustration with the current state of things, it's meant to disrupt the way you program.
  • 28. Go is a bit frustrating at first You shouldn't give into that initial frustration. Because it gets rewarding very quickly.
  • 30. Syntax Most of these examples are derived from the official tour of Go on golang.org. So if they seem too familiar, that’s probably the reason.
  • 31. Syntax: Hello World Execution starts in the main() in the "main" package. UTF-8 source code files. No special headers. No literal escaping. You can even declare unicode symbols. Ω(DoSomething()).Should(Equal("foo")) You probably shouldn't do that. Nice to know that you can though. "fmt" is where you find string formatting functions. "fmt" name is Rob Pike's doing. package main import "fmt" func main() { fmt.Println("Hello, ‫ﻳﺎ‬‫ﺑﺸﺮ‬ ") } Run
  • 32. Syntax: Variables Variables can be declared in function scope of package scope. package main import "fmt" var c, python, java bool func main() { var i int fmt.Println(i, c, python, java) } Run
  • 33. Syntax: Variables with initializers Type inference in action! package main import "fmt" var i, j int = 1, 2 func main() { var c, python, java = true, false, "no!" fmt.Println(i, j, c, python, java) } Run
  • 34. Syntax: Shorthand variable declaration Only inside a function body. Both declarations are identical. package main import "fmt" func main() { var i, j int = 1, 2 k := 3 c, python, java := true, false, "no!" fmt.Println(i, j, k, c, python, java) } Run
  • 35. Syntax: Primitive types bool string int int8 int16 int32 int64 uint uint8 uint16 uint32 uint64 uintptr float32 float64 complex64 complex128 and byte // alias for uint8 rune // alias for int32 and it represents a Unicode code point Zero values for booleans is false and for numerical types an actual 0.
  • 36. Syntax: Primitive types in action package main import ( "fmt" "math/cmplx" ) var ( ToBe bool = false MaxInt uint64 = 1<<64 - 1 z complex128 = cmplx.Sqrt(-5 + 12i) ) func main() { const f = "%T(%v)n" fmt.Printf(f, ToBe, ToBe) fmt.Printf(f, MaxInt, MaxInt) fmt.Printf(f, z, z) } Run
  • 37. Syntax: Type Conversion Unlike in a lot of other languages where automatic conversion to types with wider percision is allowed, type conversions in Go must be explicit. The expression T(v) converts the value v to the type T. package main import ( "fmt" "math" ) func main() { var x, y int = 3, 4 var f float64 = math.Sqrt(float64(x*x + y*y)) var z int = int(f) fmt.Println(x, y, z) } Run
  • 39. Syntax: Loops Your for-s, foreach-es, and your while-s.
  • 40. Syntax: Loops - For Loop Very C. Parens are not allowed. Not even optional! Body brakcets are obligatory. package main import "fmt" func main() { sum := 0 for i := 0; i < 10; i++ { sum += i } fmt.Println(sum) } Run
  • 41. Syntax: Loops - For Loop package main import "fmt" func main() { sum := 1 for ; sum < 1000; { sum += sum } fmt.Println(sum) } Run
  • 42. Syntax: Loops - While Loop package main import "fmt" func main() { sum := 1 for sum < 1000 { sum += sum } fmt.Println(sum) } Run
  • 43. Syntax: While (TRUE) Loop package main import ( "fmt" "time" ) func main() { for { fmt.Println("Tick!") time.Sleep(1000) fmt.Println("Tock!") time.Sleep(1000) } } Run
  • 44. Syntax: Conditionals - If Also very C. Also body brakcets are obligatory Again, parens are not even optional. package main import ( "fmt" "math" ) func sqrt(x float64) string { if x < 0 { return sqrt(-x) + "i" } return fmt.Sprint(math.Sqrt(x)) } func main() { fmt.Println(sqrt(2), sqrt(-4)) } Run
  • 45. Syntax: Conditionals - If with pre-statement package main import ( "fmt" "math" ) func pow(x, n, lim float64) float64 { if v := math.Pow(x, n); v < lim { return v } return lim } func main() { fmt.Println( pow(3, 2, 10), pow(3, 3, 20), ) } Run
  • 46. Syntax: Conditionals - If/else package main import ( "fmt" "math" ) func pow(x, n, lim float64) float64 { if v := math.Pow(x, n); v < lim { return v } else { fmt.Printf("%g >= %gn", v, lim) } // can't use v here, though return lim } func main() { fmt.Println( pow(3, 2, 10), pow(3, 3, 20), ) } Run
  • 47. Syntax: Conditionals - Switch Switch is a fancy if with multiple if/else clauses. package main import ( "fmt" "runtime" ) func main() { fmt.Print("Go runs on ") switch os := runtime.GOOS; os { case "darwin": fmt.Println("OS X.") case "linux": fmt.Println("Linux.") default: // freebsd, openbsd, // plan9, windows... fmt.Printf("%s.", os) } } Run
  • 48. Syntax: Conditionals - Switch case evaluation switch i { case 0: case f(): } The evaluation order of the switch case statements happens from top to bottom.
  • 49. Syntax: Functions The main building block in Go. You can create nested closures using the func keyword. package main import "fmt" func add(a int, b int) int { return a + b } func main() { sum := add(3, 1) fmt.Println("Initial sum", sum) // Closures! and first-class function values incrementSum := func() { sum += 1 } incrementSum() incrementSum() fmt.Println("Incremented sum", sum) } Run
  • 50. Syntax: Functions The type of function values is: func([argument_list]) [return_type]
  • 51. Syntax: Higher order functions We can use function types to declare some higher order functions like package main import "fmt" func add(a int, b int) int { return a + b } func subtract(a, b int) int { return a - b } func execute(a, b int, operation func(int, int) int) int { // shorthand for duplicate types return operation(a, b) } func main() { i, j := 4, 2 added := execute(i, j, add) fmt.Printf("Added %d + %d == %dn", i, j, added) subtracted := execute(i, j, subtract) fmt.Printf("Subtracted %d - %d == %dn", i, j, subtracted) } Run
  • 52. Syntax: Defer An awesome Go-first! Push clean-up code to be executed before the function returns in LIFO. Go's way of making up for not managing resources for you other than memory and CPU. package main import "fmt" func main() { defer fmt.Println("world") fmt.Println("hello") } Run
  • 53. Syntax: Stacking defer statements package main import "fmt" func main() { fmt.Println("counting") for i := 0; i < 10; i++ { defer fmt.Println(i) } fmt.Println("done") } Run
  • 54. Syntax: Pointers A Go pointer value is nothing but a typed memory addresses, much like a C pointer. *T is a pointer to a T value The zero value of a pointer is nil (no garbage values in Go).
  • 55. Syntax: Pointers This is how you declare a pointer. var p *int The & operator generates a pointer to its operand. i := 42 p = &i The * operator denotes the pointer's underlying value. fmt.Println(*p) // read i through the pointer p Dereferencing a pointer is also via the * operator. *p = 21 // set i through the pointer p Unlike C, Go has no pointer arithmetic.
  • 56. Syntax: Structs The the way of building heterogeneous aggregate custom types in Go. That's fancy talk for saying it's a collection of fields of different types. package main import "fmt" type Vertex struct { X int Y int } func main() { fmt.Println(Vertex{1, 2}) } Run
  • 57. Syntax: Structs Struct fields are accessible using the dot notation package main import "fmt" type Vertex struct { X int Y int } func main() { v := Vertex{1, 2} v.X = 4 fmt.Println(v.X) } Run
  • 58. Syntax: Struct literal notation package main import "fmt" type Vertex struct { X, Y int } var ( v1 = Vertex{1, 2} // has type Vertex v2 = Vertex{X: 1} // Y:0 is implicit v3 = Vertex{} // X:0 and Y:0 p = &Vertex{1, 2} // has type *Vertex ) func main() { fmt.Println(v1, p, v2, v3) } Run
  • 59. Syntax: Pointers to structs Quickly instantiate and populate with values a struct all at once package main import "fmt" type Vertex struct { X int Y int } func main() { v := Vertex{1, 2} p := &v p.X = 1e9 fmt.Println(v) } Run
  • 60. Syntax: Structs are your main objects If you’re coming from a strictly OOP language like Java, the only thing you would be thinking about in your program design, is classes. Classes this, classes that, classes everywhere.
  • 61. Syntax: Structs are your main objects Go creators did not like that approach where everything had to be a class. Sometimes, the simplest most correct way to express your computation, is just as a function. Go fell back to the minimalistic approach of C, where your data structures are just pure aggregate data. And you can as an added bonus, you can specify type-specific operations on each of your custom types. It’s like how in C you would declare struct s and then declare functions that all accept a pointer to the struct as their first argument by convention.
  • 62. Syntax: Struct methods Two argument lists. First one only has the "receiver" argument. Second one has zero or more argumetns of your method. Dot notation for invoking struct methods on the receiver. package main import ("fmt"; "math") type Vector struct { X float64 Y float64 } func (v Vector) Magnitude() float64 { return math.Sqrt(v.X*v.X + v.Y*v.Y) } func (v *Vector) Add(other *Vector) *Vector { return &Vector{X: v.X + other.X, Y: v.Y + other.Y} } func main() { vec := Vector{3.0, 4.0} fmt.Println(vec) fmt.Println(vec.Magnitude()) fmt.Println(vec.Add(&Vector{6.0, 4.0})) } Run
  • 63. Syntax: Arrays The way of constructing homogeneous aggregate types in Go (a sequence of values of the same type). Analogous to boring C arrays. Fixed in size. Size is part of the type. package main import "fmt" func main() { var a [2]string a[0] = "Hello" a[1] = "World" fmt.Println(a[0], a[1]) fmt.Println(a) } Run
  • 64. Syntax: Slices Slices are arrays on steroids. Go makes up for the fact that it doesn’t let you do pointer arithmetic, by giving you this much cooler and easier to use concept of slices. A slice is more or less a view into a subset of an array. []T is a slice with elements of type T. A slice's size is not reflected in its type.
  • 65. Syntax: Slices The slice literal notation lets you create slices backed by anonymous arrays very easily and populate them with values on the spot. Slices are used just like you would use an array, except for a couple of extra very neat features. package main import "fmt" func main() { p := []int{2, 3, 5, 7, 11, 13} fmt.Println("p ==", p) for i := 0; i < len(p); i++ { fmt.Printf("p[%d] == %dn", i, p[i]) } } Run
  • 66. Syntax: Slicing slices You can slice slices! Very similar to sequence slicing in Python (except that negative indices are not supported). You can slice into a slice to get a new view into its backing array, or you can slice into an already existing array to get a slice from that. package main import "fmt" func main() { p := []int{2, 3, 5, 7, 11, 13} fmt.Println("p ==", p) fmt.Println("p[1:4] ==", p[1:4]) // missing low index implies 0 fmt.Println("p[:3] ==", p[:3]) // missing high index implies len(s) fmt.Println("p[4:] ==", p[4:]) } Run
  • 67. Syntax: Slicing slices The zero value of a slice is nil.
  • 68. Syntax: Appending to slices package main import "fmt" func main() { var a []int printSlice("a", a) // append works on nil slices. a = append(a, 0) printSlice("a", a) // the slice grows as needed. a = append(a, 1) printSlice("a", a) // we can add more than one element at a time. a = append(a, 2, 3, 4) printSlice("a", a) } func printSlice(s string, x []int) { fmt.Printf("%s len=%d cap=%d %vn", s, len(x), cap(x), x) } Run
  • 69. Syntax: Appending to slices If the backing array of the slice is too short, then append() would create a new backing array big enough and use that in the returned slice.
  • 70. Syntax: Maps The native type-safe associative array in Go is the hash map, almost identical to the native map type in Python.
  • 71. Syntax: Maps You must create a map using the make() function before usage, because the zero value of map is nil and using that as a map causes in an error. You can create maps from any type to any type. package main import "fmt" type Vertex struct { Lat, Long float64 } var m map[string]Vertex func main() { m = make(map[string]Vertex) m["Bell Labs"] = Vertex{ 40.68433, -74.39967, } fmt.Println(m["Bell Labs"]) } Run
  • 72. Syntax: Map Literals package main import "fmt" type Vertex struct { Lat, Long float64 } var m = map[string]Vertex{ "Bell Labs": Vertex{ 40.68433, -74.39967, }, "Google": Vertex{ 37.42202, -122.08408, }, } func main() { fmt.Println(m) } Run
  • 73. Syntax: Map operations package main import "fmt" func main() { m := make(map[string]int) m["Answer"] = 42 fmt.Println("The value:", m["Answer"]) m["Answer"] = 48 fmt.Println("The value:", m["Answer"]) delete(m, "Answer") fmt.Println("The value:", m["Answer"]) v, exists := m["Answer"] fmt.Println("The value:", v, "Present?", exists) } Run
  • 74. Syntax: Range loops 21st century looping in Go Similar to Python sequence looping for i, v in enumerate([1, 2, 3]) and map looping for k, v in mapping.items() package main import "fmt" var pow = []int{1, 2, 4, 8, 16, 32, 64, 128} func main() { for i, v := range pow { fmt.Printf("2**%d = %dn", i, v) } } Run
  • 76. The Zen of Go: Interfaces Go resists this: - subtype polymorphism (inheritance). - parametric-type polymorphism (generics). It instead emphasizes polymorphism via interfaces.
  • 77. The Zen of Go: Interfaces Go interfaces are small. type Stringer interface { String() string } A Stringer can pretty print itself. Anything that implements String is a Stringer. Interfaces are implemented implicitly.
  • 78. The Zen of Go: Interfaces Interfaces are types. package main import "fmt" type Named interface { Name() string } func greet(someone Named) { fmt.Println("Greetings, " + someone.Name()) } type Human struct { firstName string } func (h Human) Name() string { return h.firstName } func main() { greet(Human{firstName: "Jack Bauer"}) } Run
  • 79. The Zen of Go: Interfaces A Sorting example package main import ("fmt"; "sort") type Person struct { Name string Age int } func (p Person) String() string { return fmt.Sprintf("%s: %d", p.Name, p.Age) } // ByAge implements sort.Interface for []Person based on // the Age field. type ByAge []Person func (a ByAge) Len() int { return len(a) } func (a ByAge) Swap(i, j int) { a[i], a[j] = a[j], a[i] } func (a ByAge) Less(i, j int) bool { return a[i].Age < a[j].Age } func main() { people := []Person{{"Bob", 31}, {"John", 42}, {"Michael", 17}, {"Jenny", 26}} fmt.Println(people) sort.Sort(ByAge(people)) fmt.Println(people) } Run
  • 80. The Zen of Go: Error handling
  • 81. The Zen of Go: Error handling Unchecked exceptions are evil. This is not scripting. You're building "robust" infrastructure software. "Let it crash" cannot be the default way of handling errors. Every computation that can fail must be executed with proper "error handling code".
  • 82. The Zen of Go: Error handling Memorize this pattern. You're gonna use it so much it'll haunt you in your dreams. package main import ( "fmt" ) func getMyText() (string, error) { // This could have been read from disk or a network socket return "Your text", nil } func main() { myText, err := getMyText() if err != nil { myText = "Sorry, I couldn't get your text. May I interest you in a joke?" } fmt.Println(myText) } Run
  • 83. The Zen of Go: Error handling Go chose simplest approach possible to error handling. Errors are plain regular values that implement the error interface. type error { Error() string } You should either handle an error or propagate it upwards.
  • 84. The Zen of Go: Error handling Unexpected errors should not be expected package main import ("fmt"; "regexp") func extractLongestNumber(text string) string { extractorRegexp, err := regexp.Compile("([0-9]+)") if err != nil { panic(err) // This will crash with a stack trace and the value of err } matches := extractorRegexp.FindStringSubmatch(text) if len(matches) > 1 { return matches[1] } else { return "" } } func main() { myText := "Sonmi-451" fmt.Println(extractLongestNumber(myText)) } Run
  • 85. The Zen of Go: Error handling This is so common that there's a pattern for it. package main import ("fmt"; "regexp") func extractLongestNumber(text string) string { extractorRegexp := regexp.MustCompile("([0-9]+)") matches := extractorRegexp.FindStringSubmatch(text) if len(matches) > 1 { return matches[1] } else { return "" } } func main() { myText := "Sonmi-451" fmt.Println(extractLongestNumber(myText)) } Run
  • 86. The Zen of Go: Error handling Having to handle every each possible error case manually is a common first-day complaint in Go You get used to it very quickly. You will definitely feel its reward when you run your code and find it correct and not crashing the first time.
  • 87. The Zen of Go: Packages
  • 88. The Zen of Go: Packages Packages are one more thing that newcomers clash against. Go comes with its own way of doing packages and file hierarchy for source code. Just stop fighting it.
  • 89. The Zen of Go: Packages The first thing you'll do after installing the Go SDK is setting up your $GOPATH. $GOPATH is structured like so: |- src |- bin |- pkg The import path of your packages is going to be the relative path under your $GOPATH/src directory. Doing import "coderize/awesomelib" imports the package from $GOPATH/src/coderize/awesomelib as the awesomelib package It's as simple as that. Don't invent your own system.
  • 90. The Zen of Go: Visibility Code visibility is only on the package level. Only symbols starting with an upper class letter are exported. package awesomelib type ExportedType interface { PublicAction() } type internalType struct { internalNumber int } func (a internalType) PublicAction() { /* I work in silence*/ } func internalDityWork() { /* TMI*/ } func NewAwesomeness() ExportedType { /* TMI*/ return internalType{internalNumber: 42} }
  • 91. The Zen of Go: Documentation
  • 92. The Zen of Go: Documentation No special syntax. Code documentation should be readable to humans in source code text format. // Accepts an io.Reader and does the agreed-upon computation and returns the result // or a descriptive error if something went wrong. func ExportedFunction(reader io.Reader) (Result, error) No special markup tags to describe parameters or return types. If you make sure all your exported symbols are documented, Godoc can render that into perfectly presentable HTML for you. godoc(http://godoc.org/)
  • 93. The Zen of Go: Concurrency
  • 94. The Zen of Go: Concurrency I've saved the best for last. Concurrency is a session topic on its own. Let's just skim over of what Go has to offer.
  • 95. The Zen of Go: Concurrency A goroutine is a lightweight thread managed by the Go runtime. Go routines are multiplexed over multiple actual OS threads by the runtime. go f(x, y, z) starts a new goroutine running f(x, y, z)
  • 96. The Zen of Go: Concurrency package main import ( "fmt" "time" ) func say(s string) { for i := 0; i < 5; i++ { time.Sleep(100 * time.Millisecond) fmt.Println(s) } } func main() { go say("world") say("hello") } Run
  • 97. The Zen of Go: Concurrency A channel is a typed synchronized queue. boolChannel := make(chan bool) // I created a boolean channel of type "chan bool" Channels are utilized for communication and synchronization between running goroutines. There are three things you can do on a channel: send stuff, receive stuff, or close the channel. boolChan <- = false boolChan <- = true boolChan <- = true close(boolChan) I just sent a "false" and two "true"s to the channel then closed it.
  • 98. The Zen of Go: Concurrency On the receiving end: // Listens on the given channel for three incoming boolean messages and returns true if any one // was true func getMyBooleans(myChannel chan bool) bool { firstMessage, isOpen := <- boolChan if !isOpen { return false } secondMessage, isOpen := <- boolChan if !isOpen { return firstMessage } thirdMessage, isOpen := <- boolChan if !isOpen { return firstMessage | secondMessage } return firstMessage | secondMessage | thirdMessage }
  • 99. The Zen of Go: Concurrency Too verbose? range to the rescue: // Listens on the given channel for incoming boolean messages and returns true if any one // was true func getMyBooleans(myChannel chan bool) bool { message := false for incomingMessage := myChannel { message |= incomingMessage } return message }
  • 100. The Zen of Go: Concurrency Channel sends and receives are blocking operations. So they're perfect for doing "lock-free" synchronization.
  • 101. The Zen of Go: Concurrency Here's a really dumb example that takes too much time to compute package main import "fmt" func fibonacci(i uint) uint { if i <= 1 { return 1 } return fibonacci(i-1) + fibonacci(i-2) } func main() { fmt.Println(fibonacci(41)) fmt.Println(fibonacci(41)) } Run
  • 102. The Zen of Go: Concurrency Same example but now made faster using parallelism via goroutines and channels. package main import "fmt" func compute(computation func() int) <- chan int { outputChannel := make(chan int) go func() { outputChannel <- computation() }() return outputChannel } func fibonacci(i int) int { if i <= 1 { return 1 } else {return fibonacci(i-1) + fibonacci(i-2) }} func main() { computation := func() int {return fibonacci(41)} firstResult := compute(computation) secondResult := compute(computation) // Now I'm gonna block and wait for the two results fmt.Println(<- firstResult) fmt.Println(<- secondResult) } Run
  • 103. Where to Go from here (pun intended)
  • 104. Where to Go from here (pun intended) There are still several things that I did not have the time to cover in Go. I suggest checking out the links below. Take the Go tour yourself(http://tour.golang.org/) Go for Gophers (by Andrew Gerrand)(https://talks.golang.org/2014/go4gophers.slide) Go Concurrency Patterns (by the awesome Rob Pike)(https://www.youtube.com/watch?feature=player_detailpage&v=f6kdp27TYZs) Go subreddit(http://www.reddit.com/r/golang)