簡體   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