2017-06-16 19:09



For the following code, I get the error:

type A struct{
    B_j []B `json:"A"` 
type B struct
    X string
    Y string


func main() {
    xmlFile, _ := os.Open("test.xml")

    b, _ := ioutil.ReadAll(xmlFile)

    var t root
    err2 := xml.Unmarshal(b, &rpc)
    if err2 != nil {
        fmt.Printf("error: %v", err2)

    for _, name := range t.name{
        t := A{B_j : []B{X : name.text, Y: name.type }} // line:#25

        s, _ := json.MarshalIndent(t,"", " ")


# command-line-arguments
./int2.go:25: undefined: X
./int2.go:25: cannot use name.Text (type string) as type B in array or slice literal
./int2.go:25: undefined: Y
./int2.go:25: cannot use name.type (type string) as type B in array or slice literal

In my output, I am trying to achieve something like this:

{A: {{X:1 ,Y: 2}, {X:2 ,Y: 2}, {X: 2,Y: 2}}}

Struct calling another struct to get the pattern above.

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答


  • douqiu1604 douqiu1604 4年前

    It seems you have problem at this line-

    t := A{B_j: []B{X: name.text, Y: name.type }}

    You're not creating a slice properly. Try following-

    t := A{B_j: []B{{X: name.text, Y: name.type}}}

    Let's do it better way-

    var bj []B
    for _, name := range t.name{
      bj = append(bj, B{X: name.text,Y: name.type})
    t := A{B_j: bj}
    s, _ := json.MarshalIndent(t,"", " ")      

    Sample program with static values https://play.golang.org/p/a2ZDV8lgWP

    Note: type is language keyword, do not use it as variable name.

    点赞 评论 复制链接分享