dounao1875 2018-12-08 10:14
浏览 62
已采纳

附加的第一个参数必须是slice(struct和golang)

hello i am a begginer in golang and i am working on a shopping cart app, every time i try to excute the code it shows "first argument to append must be slice" here is the code package cart

type Cart struct {
    items map[string]Item
}

type Item struct {
    id       string
    name     string
    price    float32
    quantity int
}

func NewItem(i string, n string, p float32) Item {
    return Item{
        id:       i,
        name:     n,
        price:    p,
        quantity: 0,
    }
}

func NewCart() Cart {
    return Cart{
        items: map[string]Item{}}
}

func (box *Cart) AddItem(item Item) []Item {
    box.items = append(box.items, item)
    return box.items
}

func main() {
    utils.CreateLogger("shopping-cart")
    shoppingCart := cart.NewCart()

    item1 := cart.NewItem("potato121", "Potato", 10)

    err := shoppingCart.AddItem(item1)
}
  • 写回答

1条回答 默认 最新

  • doudi8231 2018-12-08 10:22
    关注

    You get the error because you tried to add an object into a map using append(), on this line of code:

    box.items = append(box.items, item)
    

    Meanwhile the box.items type is a map[string]Item.

    type Cart struct {
        items map[string]Item
    }
    

    The append() built in function can only be used on a slice data type.


    I'm not sure what you are trying to do, whether to use a map or a slice as the type of .items. But if you want the .items property to be a slice, then change your code into this:

    type Cart struct {
        items []Item
    }
    
    func NewCart() Cart {
        return Cart{
            items: make([]Item, 0)}
    }
    

    If you want the .items property to be a map, change your code into this:

    func NewCart() Cart {
        return Cart{
            items: map[string]Item{}}
    }
    
    func (box *Cart) AddItem(item Item) map[string]Item {
        box.items[item.id] = item
        return box.items
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?