This question already has an answer here:
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?
</div>
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,
},
},
}