I have a struct Person.
type Person struct {
Firstname string
Lastname string
Years uint8
}
Then I have t
I don't even know how many ways this can go wrong...
package main
import (
"fmt"
"encoding/json"
)
type Serializable interface {
fromMap(map[string]interface{}) error
toMap() (map[string]interface{}, error)
}
type Person struct {
Firstname string
Lastname string
Years uint8
}
func (p *Person) fromMap(m map[string]interface{}) error {
b, err := json.Marshal(m)
if err != nil {
return err
}
if err := json.Unmarshal(b, p); err != nil {
return err
}
return nil
}
func (p Person) toMap() (map[string]interface{}, error) {
b, err := json.Marshal(p)
if err != nil {
return nil, err
}
m := map[string]interface{}{}
if err := json.Unmarshal(b, &m); err != nil {
return nil, err
}
return m, nil
}
func copy(p1 Serializable, p2 Serializable) error {
m1, err := p1.toMap()
if err != nil {
return err
}
m2, err := p2.toMap()
if err != nil {
return err
}
for k := range m1 {
m2[k] = m1[k]
}
if err := p2.fromMap(m2); err != nil {
return err
}
return nil
}
func main() {
p1 := Person{
"Mary",
"Jane",
26,
}
p2 := Person {
"Random",
"Lady",
26,
}
if err := copy(&p1, &p2); err != nil {
fmt.Printf("ERR: %s\n", err.Error())
return
}
fmt.Printf("%v\n", p2)
}