这是示例代码:package mainimport ( "fmt")type Product struct { Id int64 Title string AttrVals []string}type ProductAttrValView struct { Product Attr string}type ProductAttrVal struct { Attr string Product int64 Value string}func main() { p := Product{Id: 1, Title: "test", AttrVals: []string{}} var prod *Product prodViews := []ProductAttrValView{ ProductAttrValView{ Product: p, Attr: "text1" }, ProductAttrValView{ Product: p, Attr: "text2" }, ProductAttrValView{ Product: p, Attr: "text3" }, ProductAttrValView{ Product: p, Attr: "text4" }, } // collapse join View to Product with Attrs for _, pview := range prodViews { if prod == nil { prod = &pview.Product prod.AttrVals = make([]string, 0, len(prodViews)) } if pview.Attr != "" { fmt.Printf("appending '%s' to %p\n", pview.Attr, prod) // output for debug prod.AttrVals = append(prod.AttrVals, pview.Attr) } } fmt.Printf("%+v\n", prod) // output for debug}http://play.golang.org/p/949w5tYjcH这里我有一些从ProductAttrValView结构体中的DB 返回的数据,并希望将其放入Product结构体并填充Product.AttrVals它打印:&{Id:1 Title:test AttrVals:[text4]}虽然我期待这个:&{Id:1 Title:test AttrVals:[text1 text2 text3 text4]}因此,应该附加所有文本,但出于某种原因,只有最后一个元素保留在Attrs切片中。
1 回答
- 1 回答
- 0 关注
- 261 浏览
添加回答
举报
0/150
提交
取消