2017-08-04 167 views
-3

我的結構是這樣的如何初始化嵌套結構?

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

利用這個結構是這樣的方式,

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) 
} 

,我必須初始化它的單元測試,我這樣做,

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

但得到錯誤missing type in composite literal,我做錯了什麼?

+0

我嘗試的方式解釋說,它仍然沒有工作,它會顯示'不能使用結構{C接口}文字(類型結構{C接口{}}類型結構{C接口{}})*一些奇怪的錯誤*字段值中' –

回答

1

問題是B是一個匿名嵌入式結構。爲了將結構字面量定義爲另一個結構的成員,您需要給出該類型。最簡單的事情就是爲匿名類型定義結構類型。

你可以把它做這個真的很醜陋的東西,但(假設C和d是某處定義)工作:

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

謝謝@ captncraig,但它不工作,我改進了問題,有再看一遍。 –