Access struct fields of "interface{}" parameter

type s struct {
    Ou string
}

func dummy2 () {
    s1 := &s{"bunny"}
    dummy(s1)
}

WORKS:

func dummy(o *s) {
    fmt.Println(o.Ou)
}

DOES NOT WORK:

func dummy(o interface{}) {
    fmt.Println(o.Ou) // o.Ou undefined (type interface {} is interface with no methods)
}

How can I access struct fields when the struct is received as an “interface{}”

There is nothing in interface{} that guarantees that your passed in value has a field named Ou. There is not even a guarantee that your passed in value will have any fields!

You can use type assertions though to extract proper type information at runtime, roughly like this:

func dummy(o interface{}) {
  oAsserted, ok := o.(s)
  if !ok {
    panic("I fooled you about the type of the argument! It has to be an `s` in fact and is not allowed to be anything else!")
  }

  fmt.Println(oAsserted.Ou)
}

edit

Of course you can use the reflect package as well, but for now I think the type assertion is the “better” way.

Also I think it would be even better to define an interface that actually requires your data to have a method to get that Ou value and let the implementor handle the nasty details how that value is created/calculated/stored.

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.