-2

My structure is like this

type A struct{
        B struct{
           C interface{} `json:"c"`
     }
}
type C struct{
        D  string  `json:"d"`
        E  string  `json:"e"`
}

use of this struct is like this way,

func someFunc(){
  var x A
  anotherFunc(&x)
}

func anotherFunc(obj interface{}){
// resp.Body has this {D: "123", E: "xyx"} 
 return json.NewDecoder(resp.Body).Decode(obj)
}

and i have to initialise it for the unit testing and i am doing this,

x := &A{
        B: {
             C : map[string]interface{}{
                 D: 123,
                 E: xyx,
             },
        },
} 

but getting error missing type in composite literal, what am i doing wrong?

  • i tried the way explained that and it's still not working and it displays `cannot use struct {C interface} literal (type struct{C interface{}} as type struct{C interface{}}) *some weird error* in field value` – Utkarsh Mani Tripathi Aug 04 '17 at 16:52

1 Answers1

0

The problem is that B is an anonymous embedded struct. In order to define a struct literal as a member of another struct, you need to give the type. The easiest thing to do is actually define struct types for your anonymous types.

You could make it work by doing this really ugly thing though (assuming C and D are defined somewhere):

x := &A{
        B: struct{C interface{}}{
             C : map[string]interface{}{
                 D: 123,
                 E: xyx,
             },
        },
} 
captncraig
  • 22,118
  • 17
  • 108
  • 151