這是示例代碼: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它打?。?amp;{Id:1 Title:test AttrVals:[text4]}雖然我期待這個:&{Id:1 Title:test AttrVals:[text1 text2 text3 text4]}因此,應該附加所有文本,但出于某種原因,只有最后一個元素保留在Attrs切片中。
- 1 回答
- 0 關注
- 273 瀏覽
添加回答
舉報
0/150
提交
取消