http://daniel-m.github.io
As https://golang.org states,
Go is an open source programming language that makes it easy to build simple, reliable, and efficient software.
And lots more…
vgo
to be official within go1.12
).Go helped me with,
Go binary install is recommended to have the latest go version from https://golang.org/dl/ following instructions.
Go relies in the concept of workspace. The environment variable GOPATH
must
be set to an existing directory which will hold all the go packages,
binaries and precompiled packages
bin/
hello # command executable
outyet # command executable
pkg/
linux_amd64/
github.com/golang/example/
stringutil.a # package object
src/
github.com/golang/example/
.git/ # Git repository metadata
hello/
hello.go # command source
outyet/
main.go # command source
main_test.go # test source
stringutil/
reverse.go # package source
reverse_test.go # test source
golang.org/x/image/
.git/ # Git repository metadata
bmp/
reader.go # package source
writer.go # package source
... (many more repositories and packages omitted) ...
Put compiled go packages as console commands is as easy as adding GOPATH
to
the PATH
,
$ export PATH=$GOPATH/bin:$PATH
To include a package within a workspace,
$ go get github.com/user/hello
Installing a go package goes as,
$ go install github.com/user/hello
Which first <go get
> and then compiles the binaries into $GOPATH/bin
Open https://play.golang.org/ in your browsers. Throughout the presentations, links to the playground will be provided to see live performance
package main // Every go package starts with the word "package"
// Here come the package imports
import (
"fmt"
)
// Here comes the main function
func main() { // <- Opening braces must be here
// We are using the method "Println"
// included within the package "fmt"
fmt.Println("Hello, playground")
}
https://play.golang.org/p/HYUpJDXWte0
package main
import (
"fmt"
"math/rand"
)
func main() {
// Variable declaration follows the rule
// var name type [= initial_value]
var greeting string = "Hello, 世界"
fmt.Println(greeting)
fmt.Println("My favorite number is", rand.Intn(10))
}
package main
import (
"fmt"
"math/rand"
)
func main() {
// Variables can be assigned by
// the ":=" operator which infers the
// adequate types
greeting := "Hello, 世界"
fmt.Println(greeting)
fmt.Println("My favorite number is", rand.Intn(10))
}
bool // true, false
string // "Hello World!"
int int8 int16 int32 int64 // Several flavors of integers
uint uint8 uint16 uint32 uint64 uintptr
byte // alias for uint8. Size guaranteed
rune // alias for int32
// represents a Unicode code point. Size guaranteed
float32 float64 // single and double precision
complex64 complex128 // Yes!, complex numbers natively supported
https://play.golang.org/p/Fy3IxY-LLdI
package main
import (
"fmt"
"math/rand"
)
// Greeter returns a greeting string
func Greeter() string {
return "Hello, 世界"
}
// Number returns a random int seeded with seed
func Number(seed int) int {
return rand.Intn(seed)
}
func main() {
fmt.Println(Greeter())
fmt.Println("My favorite number is", Number(10))
}
https://play.golang.org/p/yUPdKi-zeHL
package main
import (
"fmt"
"math/rand"
)
// GreeterNumber returns a greeting string
// and a number.
// Yes, go supports multiple return functions
func GreeterNumber(seed int) (string, int) {
return "Hello, 世界", rand.Intn(seed)
}
func main() {
// Variables can be assigned by
// the ":=" operator which infers the
// adequate types
greet, num := GreeterNumber(10)
fmt.Println(greet)
fmt.Println("My favorite number is", num)
}
“Defers” function call
https://play.golang.org/p/TD6SZBXwn_r
package main
import "fmt"
func main() {
defer fmt.Println("print last...")
defer fmt.Println("You didn't expected me to")
defer fmt.Println("I bet,")
fmt.Println("Hey there!")
fmt.Println("Ready to see something amazing?")
}
https://play.golang.org/p/g5TY4wb916e
package main
import (
"fmt"
)
func abs(x float64) float64 {
if x < 0 {
return abs(-x)
}
return x
}
func main() {
fmt.Println(abs(2), abs(-4))
}
https://play.golang.org/p/zqAHNoFiUZO
package main
import (
"fmt"
)
func abs(x float64) float64 {
if x < 0 {
return abs(-x)
} else {
return x
}
}
func main() {
fmt.Println(abs(2), abs(-4))
}
func abs(x float64) float64 {
if x < 0 {
return abs(-x)
} else if x == 0 {
return 0
} else {
return x
}
}
A single loop structure rules them all,
https://play.golang.org/p/HwJ5nXetGDV
// single condition for looping
i := 1
for i <= 3 {
fmt.Println(i)
i = i + 1
}
A single loop structure rules them all,
https://play.golang.org/p/HwJ5nXetGDV
// A classic C-like initial/condition/after `for` loop.
for j := 7; j <= 9; j++ {
fmt.Println(j)
}
A single loop structure rules them all,
https://play.golang.org/p/HwJ5nXetGDV
// `for` without a condition will loop repeatedly
// until you `break` out of the loop or `return` from
// the enclosing function.
for {
fmt.Println("loop")
break
}
A single loop structure rules them all,
https://play.golang.org/p/HwJ5nXetGDV
// You can also `continue` to the next iteration of
// the loop.
for n := 0; n <= 5; n++ {
if n%2 == 0 {
continue
}
fmt.Println(n)
}
https://play.golang.org/p/A1oG39orUpZ
[n]T
is an array of n values of type T
.func main() {
var a [2]string
a[0] = "Hello"
a[1] = "World"
fmt.Println(a[0], a[1])
fmt.Println(a)
// Or the short declaration
// also known as "array literal"
primes := [6]int{2, 3, 5, 7, 11, 13}
fmt.Println(primes)
}
[]T
is a slice with elements of type T
.a[low : high]
high is not included.primes := [6]int{2, 3, 5, 7, 11, 13}
var s []int = primes[1:4]
fmt.Println(s) // Outputs: [3 5 7]
make
operatorhttps://play.golang.org/p/ZwE_3e063GG
a := make([]int, 5) // len(a)=5
fmt.Printf("len=%d cap=%d %v\n", len(a), cap(a), a)
// Outputs:
// len=5 cap=5 [0 0 0 0 0]
b := make([]int, 0, 5)
fmt.Printf("len=%d cap=%d %v\n", len(b), cap(b), b)
// Outputs:
// b len=0 cap=5 []
https://play.golang.org/p/-axSPJOLI1A
make
function returns a map of the given type, initialized and ready for use.// Create an array of float64
udea := [2]float64{6.2554189, -75.5920199}
// Allocate a map from string to [2]float64
sitios := make(map[string][2]float64)
// assign element to map
sitios["udea"] = udea
fmt.Println(sitios)
// Outputs :[6.2554189 -75.5920199]]
https://play.golang.org/p/NtNGEbZokIX
var pow = []int{1, 2, 4, 8, 16, 32, 64, 128}
for i, v := range pow {
fmt.Printf("2**%d = %d\n", i, v)
}
https://play.golang.org/p/WmxXd4xsftV
var pow = map[int]int{0:1, 1:2, 2:4, 3:8}
for k, v := range pow {
fmt.Printf("2**%d = %d\n", k, v)
}
func compute(fn func(float64, float64) float64) float64 {
return fn(3, 4)
}
func main() {
hypot := func(x, y float64) float64 {
return math.Sqrt(x*x + y*y)
}
fmt.Println(hypot(5, 12))
fmt.Println(compute(hypot))
fmt.Println(compute(math.Pow))
}
Go has pointers, but lack pointer arithmetic https://play.golang.org/p/O0qc2lYGuAK
package main
import "fmt"
func main() {
i, j := 42, 2701
p := &i // point to i
fmt.Println(p) // who is p?
fmt.Println(*p) // read i through the pointer
*p = 21 // set i through the pointer
fmt.Println(i) // see the new value of i
p = &j // point to j
fmt.Println(p) // who is p now?
*p = *p / 37 // divide j through the pointer
fmt.Println(j) // see the new value of j
}
The type *T
is a pointer to a T
value. Its zero value is nil
.
var p *int // Will store a pointer (nil)
The &
operator generates a pointer to its operand.
i := 42 // Short int declaration
p = &i // p now points to i
The *
operator denotes the pointer’s underlying value.
fmt.Println(*p) // read i through the pointer p
+p = 21 // set i through the pointer p
This is known as “dereferencing” or “indirecting”.
https://play.golang.org/p/zQWVtBPH3-w
// We declare the Person structure
type Person struct {
Name string
LastN string
Email string
}
func main() {
john := Person{"John","Doe", "john@doe.jd"}
fmt.Println("The person is", john)
}
https://play.golang.org/p/OdmLz3h-AbI
// Mumble returns a greeting string
func (p *Person) Mumble() string {
return "Hey, my name is " + p.Name + " " + p.LastN
}
// Speak Mumbles to standard output
func (p *Person) Speak() {
fmt.Println(p.Mumble())
}
https://play.golang.org/p/OdmLz3h-AbI
func main() {
// Struct literal for John
john := Person{"John", "Doe", "john@doe.jd"}
// We can see that the standard output handles
// Data streaming easily (Not overload required)
fmt.Println("The person is", john)
// The struct is edowed with two methods
fmt.Println(john.Mumble())
// Tell'em John!
john.Speak()
}
Create Structure instances with New...
functions,
type Something {
...
}
...
func NewSomething(...) *Something {
...
}
Create Structure instances with New...
functions,
type Something {
...
}
...
func NewSomething(...) *Something {
...
}
https://play.golang.org/p/a_DtRz6gvub
// Cow structure
type Cow struct {
Color string
}
// Cow makes "moo"
func (c *Cow) MakeSound() {
fmt.Println("Moo")
}
https://play.golang.org/p/a_DtRz6gvub
// Pigeon structure
type Pigeon struct {
Age int
}
// Pidgeon makes "Coo"
func (p *Pigeon) MakeSound() {
fmt.Println("Coo")
}
https://play.golang.org/p/a_DtRz6gvub
// Dog structure
type Dog struct {
Age int
Color string
Name string
}
// Dogs bark
func (d *Dog) MakeSound() {
fmt.Println("Bark!")
}
// Dogs can roll too
func (d *Dog) Roll() {
fmt.Println("Dog", d.Name, "rolls over")
}
https://play.golang.org/p/a_DtRz6gvub
// Sounder groups all types which can MakeSound
type Sounder interface {
MakeSound()
}
https://play.golang.org/p/a_DtRz6gvub
// Interfaces are types
// We can instance a Sounder
var animal Sounder
// Pidgeons comply the interface
animal = &Pigeon{1}
animal.MakeSound()
// Cows comply the interface
animal = &Cow{"black"}
animal.MakeSound()
// Dogs comply the interface
animal = &Dog{3, "Black and White", "Max"}
animal.MakeSound()
https://play.golang.org/p/2V3uawcTh3K
go function_call()
.https://play.golang.org/p/2V3uawcTh3K
// One prints Hello 10 times
func One() {
for i := 0; i < 10; i++ {
fmt.Println("Hello")
}
}
// Two prints World 10 times
func Two() {
for i := 0; i < 10; i++ {
fmt.Println("World")
}
}
https://play.golang.org/p/2V3uawcTh3K
func main() {
// Starting a couple of go routines
go Two()
go One()
// Uncomment below :)
// go time.Sleep(3 * time.Second)
time.Sleep(3 * time.Second)
}
<-
.ch <- v // Send v to channel ch.
v := <-ch // Receive from ch, and
// assign value to v.
Like maps and slices, channels must be created before use:
ch := make(chan int)
// Greet sends "Hello World" through a channel
func Greet(c chan string) {
// Text to be sent
greet := "Hello world"
// Loop over the string
for _, v := range greet {
// send each character on the channel
c <- string(v)
}
// Close the channel once the operation is done
close(c)
}
// We need to create the channel first
c := make(chan string)
// Go routine for the Greet function
go Greet(c)
// Iterate over the input channel
for i := range c {
fmt.Println(i)
}
godoc
tool.// LogFormatter initiates the beginning of a new LogEntry per request.
// See DefaultLogFormatter for an example implementation.
type LogFormatter interface {
NewLogEntry(r *http.Request) LogEntry
}
// LogEntry records the final log when a request completes.
// See defaultLogEntry for an example implementation.
type LogEntry interface {
Write(status, bytes int, elapsed time.Duration)
Panic(v interface{}, stack []byte)
}
https://play.golang.org/p/DlJRghK5eRQ
"testing"
go test
package_test.go
import (
"testing"
)
// Squared squares integer numbers
func Squared(number int) int {
return number * number
}
https://play.golang.org/p/DlJRghK5eRQ
// testCase is a struct for the test cases
type testCase struct {
input int
wants int
}
https://play.golang.org/p/DlJRghK5eRQ
// TestSquared tests the function Squared
func TestSquared(t *testing.T) {
testCases := []testCase{{2, 4}, {3, 9}, {10, 100}, {5, 25}}
// Uncomment below :)
//testCases = []testCase{{2, 4}, {3, 9}, {10, 100}, {5, 25}, {2,2}}
// Iterate over the testCases slice
for _, test := range testCases {
if Squared(test.input) != test.wants {
t.Errorf("Failed test, expected %d got %d", test.wants, Squared(test.input))
}
}
}
Logging
with "log"
.Writters
and Readers
."sync"
package to synchronize go
routines.vgo
and package versioning.select
operation.