4 回答
TA贡献1811条经验 获得超4个赞
让我们考虑这个解决方案:
arrDetails := map[int]map[string]string{}
index := 0
for _, orderdetails := range ordersfromdb {
arrDetails[index] = map[string]string{} // you have to initialize map
arrDetails[index]["OrderNumber"] = "001"
arrDetails[index]["customernum"] = "cust_001"
arrDetails[index]["orderstatus"] = "open"
arrDetails[index]["orderprice"] = "200"
index++
}
要将结果转换为 json(正如我看到你在对@liao yu 的回答的评论中提出的问题),我们应该学习更多关于标签的知识:
import (
"encoding/json"
"fmt"
)
type OrderDetails struct {
Number string `json:"number"`
Customer string `json:"customer"`
Status string `json:"status"`
Price string `json:"price"`
}
func main() {
ordersfromdb := []int{1, 2, 3}
var arrDetails []OrderDetails
for _, v := range ordersfromdb {
arrDetails = append(arrDetails, OrderDetails{
Number: fmt.Sprintf("order_number_%v", v),
Customer: fmt.Sprintf("customer_%v", v),
Status: fmt.Sprintf("order_status_%v", v),
Price: fmt.Sprintf("$%v", v),
})
}
data, err := json.Marshal(arrDetails)
if err != nil {
panic(err)
}
fmt.Println(string(data))
}
TA贡献1831条经验 获得超9个赞
你可以试试这个:
import "fmt"
func main() {
var arrDetails []map[string]string
var index int = 0
//for _, orderdetails := range ordersfromdb {
for i:=0; i<5;i++ {
detail := make(map[string]string)
detail["OrderNumber"] = "001"
detail["customernum"] = "cust_001"
detail["orderstatus"] = "open"
detail["orderprice"] = "200"
arrDetails = append(arrDetails, detail)
index++
}
fmt.Printf("Hello, playground %+v", arrDetails )
}
TA贡献1785条经验 获得超8个赞
正如您在此处将arrDetails变量定义为多维切片一样[][]string。这意味着您不能将 a 分配string给它keys,而可以将字符串分配为值。
你可以像下面我提到的那样做你的代码。
package main
import (
"fmt"
)
func main() {
var arrDetails [][]string
var s []string
var index int
for i:=0; i<5;i++ {
s = []string{"001", "cust_001", "open", "200"}
arrDetails = append(arrDetails, s)
index++
}
fmt.Printf("Hello, playground %+v", arrDetails )
}
或者,如果你想要keys配对value,那么你必须用作map:
var arrDetails map[string]string
TA贡献1775条经验 获得超8个赞
我按如下方式填充多维数组
arrDetails[index][0] = "001"
arrDetails[index][1] = "cust_001"
arrDetails[index][2] = "open"
arrDetails[index][3] = "200"
- 4 回答
- 0 关注
- 148 浏览
添加回答
举报