miguelmota/golang-for-nodejs-developers

Destructuring in Go

hendrasan opened this issue · 5 comments

I'm still learning Go so might be wrong, but can't you do destructuring like this so you don't need to have an additional function?


import "fmt"

type Obj struct {
	Key string
	Value string
}

func main() {
	obj := Obj{
		Key: "foo",
		Value: "bar",
	}
	
	key, value := obj.Key, obj.Value

	fmt.Println(key, value)
}```

@hendrasan you are correct. The example has been updated. Thanks!

ToJen commented

Is there a Golang equivalent of this:

let person = {
 name: "test", 
 age: 13
}

let student = {
  ...person,
  school: "harvard"
}
console.log(student)

/*
Object {
  age: 13,
  name: "test",
  school: "harvard"
}
*/

The goal is to pass attributes of any Go struct into a new struct with an extra attribute.

@ToJen this is the closest thing I think

package main

import "fmt"

func main() {
	person := map[string]interface{}{
		"name":   "test",
		"age":    13,
		"school": "stanford",
	}

	student := map[string]interface{}{
		"school": "harvard",
	}

	for k, v := range person {
		if _, ok := student[k]; !ok {
			student[k] = v
		}
	}

	fmt.Println(student) // map[age:13 name:test school:harvard]
}

https://play.golang.org/p/BlVCIjH93vA

ToJen commented

Thanks, the use case is more like this:

type TypeA struct {
  name string
  age    int
}

type TypeB struct {
  id               string
  capacity    int
}

type TypeC struct {
  // accept any other struct's fields
  school string
}

@ToJen I believe this is what you're looking for:

package main

import "fmt"

type TypeA struct {
	name string
	age  int
}

type TypeB struct {
	id       string
	capacity int
}

type TypeC struct {
	TypeA
	TypeB
	school string
}

func main() {
	typeA := TypeA{
		name: "alice",
		age:  18,
	}

	typeB := TypeB{
		id:       "a123",
		capacity: 1,
	}

	typeC := TypeC{
		TypeA:  typeA,
		TypeB:  typeB,
		school: "harvard",
	}

	fmt.Println(typeC.name)     // "alice"
	fmt.Println(typeC.age)      // 18
	fmt.Println(typeC.id)       // "a123"
	fmt.Println(typeC.capacity) // 1
	fmt.Println(typeC.school)   // "harvard"
}

https://play.golang.org/p/jhZe_HjGXja