-2

Given the following types:

type (
    Parent struct {
        name string
        surname string
    }

    Child struct {
        *Parent
        sport String
    }
)

...

func (p *Parent) GetSport() string {
   return ((*Child)(p)).sport // does not work
}

How do I convert *Parent to *Child?

j3d
  • 9,492
  • 22
  • 88
  • 172
  • 1
    So you expect that after converting `sport` property will appear? – u_mulder Oct 28 '17 at 11:35
  • Yes, I know `Parent` is also a `Child` and I want to cast it. – j3d Oct 28 '17 at 11:37
  • Make sure you know how to use search https://stackoverflow.com/questions/37416188/convert-struct-to-struct-in-golang – u_mulder Oct 28 '17 at 11:38
  • Or https://stackoverflow.com/questions/24613271/golang-is-conversion-between-different-struct-types-possible – u_mulder Oct 28 '17 at 11:39
  • I know how to use search. What you suggest is not what I'm looking for. I need to conver a pointer of type `*Parent` to a pointer of type `*Child`. – j3d Oct 28 '17 at 11:45
  • You know __what__ is pointer, right? – u_mulder Oct 28 '17 at 11:51
  • @j3d Are you sure you want to convert `*Parent` to `*Child` and not the other way around? Because from my understanding (I'm not an expert in go), based on the struct definition, there is no way `Parent` can carry information about `sport`, how can you think that is supposed to work? – har07 Oct 28 '17 at 12:37
  • I see... got the point. See my own answer ;-) – j3d Oct 28 '17 at 13:05

1 Answers1

3
func (p *Parent) Convert() *Child {
   return &Child{p, ""}
}

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

The problem is there’s no data about sport. So we have to put empty line.

Eugene Lisitsky
  • 12,113
  • 5
  • 38
  • 59