destructuring


Node.js

  1. const obj = { key: 'foo', value: 'bar' }
  2. const { key, value } = obj
  3. console.log(key, value)

Output

  1. foo bar

Go

  1. package main
  2. import "fmt"
  3. type Obj struct {
  4. Key string
  5. Value string
  6. }
  7. func (o *Obj) Read() (string, string) {
  8. return o.Key, o.Value
  9. }
  10. func main() {
  11. obj := Obj{
  12. Key: "foo",
  13. Value: "bar",
  14. }
  15. // option 1: multiple variable assignment
  16. key, value := obj.Key, obj.Value
  17. fmt.Println(key, value)
  18. // option 2: return multiple values from a function
  19. key, value = obj.Read()
  20. fmt.Println(key, value)
  21. }

Output

  1. foo bar
  2. foo bar