roberto bampi @ trenta3dev
Go is a statically typed, compiled, garbage collected language with first class support to concurrent programming.
It was initially developed at Google by Robert Griesemer, Rob Pike and Ken Thompson in 2007 to ease the development of large server systems.
It was open sourced in 2009 and version 1.0 (stable) was reached in 2012.
Go has excellent out of the box tooling support:
package main
import "fmt"
func main(){
fmt.Println("Hello Go!")
}
go run compiles and runs the programroberto@immortal ~ $ go run main.go
Hello Go!
multiple assignments and multiple returns from functions
package main
import "fmt"
func doubleAndTriple(n int) (int, int){
return n*2, n*3
}
func main(){
a, b := doubleAndTriple(3)
fmt.Printf("a: %d, b: %d\n", a, b)
a, b = b, a
fmt.Printf("a: %d, b: %d\n", a, b)
}
Unlike C, types are declared after variable namevar a string
And, unlike C, semicolons are optional !for i := 0; i < 255; i++ { // loop with number
fmt.Println("go is cool")
}
for _, val := range []string{"go", "is", "cool"} { // loop over slice
fmt.Println(val)
}
for { // loop forever
fmt.Println("go is cool")
}
if err, res := http.Get("http://google.com"); err != nil {
// deal with error
}
Object orientation in go is achieved by implementing methods on structs.
Structs are just like C structs.
Inheritance is not allowed, embedding is the way to add functionality to a struct in go.
package main
import "fmt"
type Animal struct {
Color string
}
func (a Animal) String() string {
return "I am a " + a.Color + " animal"
}
type Cat struct {
Animal
}
func main() {
jerry := Animal{Color: "brown"}
fmt.Println(jerry)
tom := Cat{}
tom.Color = "grey"
fmt.Println(tom)
}
One feature that really makes the Go type system shine is the way interfaces are handled.
An interface is just a list of methods that a struct must implement. The real power of it is that, unlike other languages (java, C#, ...), the struct implementing the interface does not need to explicitly declare so.
Remember the lousy animal example from earlier ?
func (a Animal) String() string { ...
Animal was implementing the `Stringer` interface which, when implemented, allows the fmt.Println function to print it !
Go was designed with concurrency in mind.
Concurrency is not (only) about running things in parallel, it is mostly about designing the software in small components that can communicate with each other in an asynchronous fashion.
To achieve this, go provides:
package main
import "fmt"
import "time"
func tick(t time.Duration) <-chan bool {
c := make(chan bool)
go func() {
for {
time.Sleep(t)
c <- true
}
}()
return c
}
func main() {
tick := tick(1 * time.Second)
for {
select {
case <-tick:
fmt.Println("go is cool!")
}
}
}
roberto.bampi@gmail.com
github.com/gigaroby