0

Interfaces in go consist of a reference to a struct - does this mean they cannot be copied / dereferenced properly? I have recreated my problem below:

package main

import (
    "fmt"
    "encoding/json"
)

type Animal interface {
    getName() string
}

type Dog struct {
    Name string
}
func (d Dog) getName() string {; return d.Name; }

func getTwo(a Animal) []Animal {
    b := a
    json.Unmarshal([]byte(`{"Name":"Bella"}`), a)
    json.Unmarshal([]byte(`{"Name":"Buster"}`), b)

    return []Animal{a, b}
}

func main() {
    l := getTwo(&Dog{})

    fmt.Printf("dog 1 is called: %s\n", l[0].(*Dog).getName())
    fmt.Printf("dog 2 is called: %s\n", l[1].(*Dog).getName())
}

This currently outputs:

dog 1 is called: Buster

dog 2 is called: Buster

Is it possible to dereference b from a (preferably without reflection)? I'm looking for an answer which only modifies the main or getTwo method (the rest of the methods are mocked). Obviously getTwo should be able to handle both Dogs and other Animals (like it currently does)

Sjon
  • 4,989
  • 6
  • 28
  • 46

0 Answers0