This document introduces Go and discusses its suitability for building APIs and web applications. It notes that Go was created by Google to address issues with other languages like long compilation times and dependencies. It provides examples of using Go for URL shorteners, notifications, tracking, and map reduce. It also covers Go fundamentals like packages, objects without classes using composition, functions, errors vs exceptions, goroutines, channels, and concurrency patterns. Finally it offers some tips and lists popular Go web frameworks.
15. No classes?
const roleAdmin = "admin";
type People {
Public
Email string
Registered time.Time
role string
}
Private
func (p *People) IsAdmin() bool {
return (p.role == roleAdmin)
}
Sort of like
$this
16. No classes?
type User interface {
IsAdmin() bool
}
func printUser(u User) {
fmt.Println("Is Admin:", u.IsAdmin())
}
u := &People{
Email: "test@email.com",
role: roleAdmin,
}
printUser(u)
17. Instead of inheritance, composition
type Person interface {
Name() string
}
type User struct {
Person
Email string
}
type RegisteredUser struct {
Person
Name string
}
func (u *User) Name() string {
return u.Email
}
func (r *RegisteredUser) Name() string {
return u.name
}
u := &User{
Email: "test@email.com",
}
r := &RegisteredUser{
name: "Mariano",
}
fmt.Println(u.Name(), r.Name()
Sort of like traits
18. Functions
Multiple values
func do(a int64, b int64) (x int64, y float64) {
x = a * b
y = float64(a / b)
return
Named return
}
Closure
func main() {
g := func(n int64) (int64, float64) {
return do(n, 10)
}
fmt.Println(g(50))
}
21. Goroutines
func main() {
go func() {
for {
if !worker.Work() {
break
}
}
}()
fmt.Println("Waiting...")
time.Sleep(5 * time.Second)
}
Not very nice. What can we
do to know goroutine is done
22. Channels
func main() {
finished := make(chan bool)
go func() {
defer close(finished)
for {
if !worker.Work() {
finished <- true
break
}
}
}()
<-finished
}
25. Select in channels
go func() {
for {
select {
case m := <- messages:
fmt.Println("[MESSAGE]", m)
case p := <- pings:
fmt.Println("[PING]", p)
}
}
}()
<- time.After(time.Second * 10)
#12: * Map reduce: el master divide el problema en problemas mas chicos, se los da a workers. (Mapeo). Luego el worker devuelve el resultado, el master collecciona los resultados de sus workers, y genera su resultado (Reduce)
#22: * La rutina se ejecuta en un threadpool. Dependiendo del compilador (gccgo, etc) puede ser un thread por routine, o no