07 - Structs, Embedded Structs & function receiver


Le code source écrit pendant l’épisode:

package main

type todo struct {
  text string
  done bool
}

// function with receiver
// func (receiver) identifier(args) (returns)
func (t *todo) toggle() {
  t.done = !t.done
}

type user struct {
  name  string
  todos []*todo
}

func (u user) show() {
  fmt.Printf("Name : %s\n", u.name)
  fmt.Printf("Todos: %d\n", len(u.todos))

  for _, t := range u.todos {
    fmt.Printf("<Todo text=%s done=%v>\n", t.text, t.done)
  }
}

func (u *user) addTodo(t *todo) {
  u.todos = append(u.todos, t)
}

func main() {
  u := user{name: "Kurosoki ichigo"}

  t := todo{text: "Bien faire les choses cette fois."}
  t.toggle()
  u.addTodo(&t)

  u.show()
  t.toggle()

  u.show()
}