dongzheng8463 2017-11-28 13:50
浏览 100
已采纳

将参数解析为布尔值或仅在switch语句中使用字符串

I'm coming across a few situations where I would like to use routing to change some Is_Active fields in my database but I'm curious about performance.

Let's have a route handler as so:

func testHandler(r *mux.Router) {
    r.HandleFunc("/test/{status}" statusHandler).Methods("GET")
}

Now that parameter will only ever be 0 or 1, unless the user tries something else but either way nothing will happen unless it's 0 or 1. My question is, is it faster to parse the string into a boolean which would involve bringing in the strconv package or would it be faster to just do a switch on the string?

Example of both:

func statusHandler(w http.ResponseWriter, r *http.Request) {
    v := mux.Vars(r)
    active, err := strconv.ParseBool(v["status"])
    // Handle err

    if active {
      // Do something
    } else {
      // Do something else
    }
}

or

func statusHandler(w http.ResponseWriter, r *http.Request) {
    v := mux.Vars(r)

    switch v["status"] {
        case "0":
            // Do something
        case "1":
            // Do something else
        default:
            // Throw 500 Error
    }
}
  • 写回答

1条回答 默认 最新

      报告相同问题?

      相关推荐 更多相似问题

      悬赏问题

      • ¥15 关于用matlab进行光束整形的问题
      • ¥15 vs code编译器 C语言刚学,想的有点复杂
      • ¥15 航班订票系统函数无法运行
      • ¥20 VS2022无法启动程序,如何解决?(语言-c++|开发工具-visual studio)
      • ¥15 c语言可以做出完整的吗有人看看吗
      • ¥15 电脑流氓插件处理方法
      • ¥15 问一下这个可调恒流源电路用哪个电源接口比较好,想用tapec接口仅作为电源接口这个引脚怎么连啊
      • ¥30 Abaqus做建模的时候网格没办法收敛是为什么?
      • ¥15 车牌识别摄像镜头,httppost,nodejs
      • ¥20 腾讯云托管与本地测试 GET请求获取返回值 完全不同