繁体   English   中英

For 循环遍历切片并使结构链接到切片

[英]For loop through the slice and making the struct to be linked to a slice

我需要对切片进行 for 循环以显示结构的值。 我想做一些家庭为[0],食物为[1],饮料为[2]的事情

package main

import (
    "fmt"
)

type item struct {
    Category[3] int
    Quantity int
    Unitcost float64
}

categoryslice = []string{"Household","Food","Drink"}


func main() {
    shoppinglists := []shoppinglist{

        {
            Category: categoryslice[0],
            Quantity: 3,
            Unitcost: 1,
        },
        {
            Category: categoryslice[1],
            Quantity: 1,
            Unitcost: 3,
        },
    }

    fmt.Println("Shopping List Contents:")
    for _, x := range shoppinglists {
        fmt.Println("Category: ", x.Category," Quantity: ", x.Quantity, " Unit Cost: ", x.Unitcost)
    }
    
}

不是很推荐,但您可以将struct转换为map并迭代生成的map

将此方法添加到您的结构中:

func (sl *shoppinglist) ToMap() map[string]interface{} {
    return map[string]interface{}{
        "category":  sl.Category,
        "items":     sl.Items,
        "quantity":  sl.Quantity,
        "unit_cost": sl.Unitcost,
    }
} 

然后像这样遍历切片中的每个 map

for _, e := range arr {
    for k ,v := range e.ToMap() {
        fmt.Printf("%s: %v\n", k, v)
    }
    fmt.Println()
}

希望我有所帮助:)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM