doujia3441 2018-10-24 02:32
浏览 41
已采纳

确定删除操作是否实际上删除了映射中的现有键

I have a map called nearby

func Delete(w http.ResponseWriter, r *http.Request) {
    params := mux.Vars(r)
    delete(nearby, params["id"])
}

I want to find out if the delete() call actually found a key to delete, I tried reading the return value:

func Delete(w http.ResponseWriter, r *http.Request) {
    params := mux.Vars(r)
    result := delete(nearby, params["id"])
}

but the compiler didn't like that - how can I find out if a key/val was deleted?

  • 写回答

2条回答 默认 最新

  • duange2971 2018-10-24 02:45
    关注

    Probe the map before deleting the value:

    func Delete(w http.ResponseWriter, r *http.Request) {
        params := mux.Vars(r)
        _, deleted := nearby[params["id"]]
        delete(nearby, params["id"])
        fmt.Println(deleted)
    }
    

    This snippet and the code in the question have a data race because HTTP handlers can be called concurrently. Add a mutex to protect the map.

    var (
        nearby = make(map[string]string)
        mu     sync.Mutex
    )
    
    func Delete(w http.ResponseWriter, r *http.Request) {
        params := mux.Vars(r)
        mu.Lock()
        _, deleted := nearby[params["id"]]
        delete(nearby, params["id"])
        mu.Unlock()
        fmt.Println(deleted)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 结果有了,想问一下这个具体怎么输入
  • ¥15 怎么修改鸿蒙app的UI及功能设计
  • ¥15 帮我利用jupyter 运行一个正确的代码
  • ¥15 如何使用Gephi软件和Python包中的GephiStreamer交互
  • ¥15 sqlite加密问题咨询
  • ¥15 appdesigner接收不到udp组播的数据
  • ¥15 verilog 非阻塞赋值下的移位拼接错误
  • ¥100 两个按钮控制一个LED
  • ¥30 如何用python的GephiStreamer连接到gephi中,把Python和Gephi的具体操作过程都展示,重点回答Gephi软件的调试,以及如果代码的端口在浏览器中无法显示怎么处理
  • ¥15 ansys机翼建模肋参数