简体   繁体   中英

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

I need to do a for loop through the slice to display the values of the structs. I want to do something where household would be [0],food would be [1] and drink to be [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)
    }
    
}

Not really recommended, but you can convert the struct into a map and iterate over the resulting map

add this method to your struct:

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

then iterate over each map in the slice like this

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

hope I helped:)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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