golang

Go notes

Books

Concurrency vs Parallelism

  • Parallelism is the process by which a CPU executes multiple tasks at the same time, while concurrency is the CPU’s ability to switch between multiple tasks that start, run, and complete while overlapping one another. In other words, parallel programs handle many operations at once, while concurrent programs can switch between many operations over the same period of time.

Embedding and Chaining

Embedding

type Dog struct{}
func (d Dog) Speak() {
  fmt.Println("woof")
}

type Husky struct {
 Dog
}

func main() {
  h := Husky{Dog{}}
  h.Speak() // equal to h.Dog.Speak()
}

Chaining

  • We can use chaining to create a middleware like validators,...
  type Cat struct{}
  func (c Cat) Speak() {
    fmt.Println("Meow")
  }

  type Dog struct{
    Tail bool
  }

  type Husky struct{
    Dog
    Speaker
  }

  type Speaker interface{
    Speak()
  }

  type SpeakerPrefixer struct {
    Speaker
  }

  func (sp SpeakerPrefixer) Speak() {
    fmt.Print("Prefix: ")
    sp.Speaker.Speak()
  }

  func main() {
    // h := Husky{Dog{Tail: true}, Cat{}}
    // h.Speak() // Meow
    //. fmt.Println(h.Tail) // true
    h := Husky{Dog{Tail: true}, SpeakerPrefixer{Cat{}}}
    h.Speak() // Prefix: Meow
  }