从切片中删除特定元素

时间:2019-09-01 13:57:01

标签: arrays go

我得到了以下代码:

type TimeSlot struct {
    ID int64 `json:"id" sql:"auto_increment"`
}

type Reserve struct {
    ID int64 `json:"id" sql:"auto_increment"`
    TimeSlot TimeSlot `gorm:"foreignkey:time_slot_id;association_autoupdate:false" json:"-"`
    TimeSlotID int64 `json:"time_slot_id"`
}

func GetFreeTimeSlotList (w http.ResponseWriter, r *http.Request) {
    var TimeSlotList models.TimeSlot
    List, err := models.TimeSlotStore.GetArray(&TimeSlotList)
    if err != nil {
        fmt.Fprintf(w, "Error GetArray of TimeSlots", err)
        w.Write([]byte(err.Error()))
        return
    }

    BookingReserveList, err := models.ReserveStore.GetArray(&models.Reserve{})
    if err != nil {
        fmt.Fprintf(w, "Error Getting booking Array!", err)
        fmt.Println("Error Getting booking Array!")
        return
    }

    *BookingReserveList = append(*BookingReserveList)
    for _, v := range *BookingReserveList {
        if v.TimeSlotID == TimeSlotList.ID {

        }
    }

    w.Header().Set("Content-Type", "application/json")
    err = json.NewEncoder(w).Encode(List)
    if err != nil {
        fmt.Fprintf(w, "Error encoding JSON", err)
        w.Write([]byte(err.Error()))
        return
    }

}


只能在TimeSlotID的基础上创建保留。我正在写一种方法来输出所有未使用的插槽。但我现在停留在这一点:

for _, v := range *BookingReserveList {
        if v.TimeSlotID == TimeSlotList.ID {

如何从基本切片中减去元素并显示结果?

1 个答案:

答案 0 :(得分:0)

假设您希望预订预订清单的所有元素都与某个时间段不匹配,只需创建另一个空列表并添加所需的所有元素,然后返回即可。像这样:

var list []*List
for _, v := range *BookingReserveList {
    if v.TimeSlotID != TimeSlotList.ID {
        list = append(list,v)