在我的 golang 应用程序中,我根据表单输入将一些全局变量设置为 true,然后发现它们在后续函数中使用时已更改为 false。问题,在 golang 中声明和设置布尔值的正确方法是什么?var withKetchup boolvar withMustard boolfunc orderProcess(w http.ResponseWriter, r *http.Request){ r.ParseForm() withKetchup := r.FormValue("withKetchup") //set to true (in form js form selection) withMustard := r.FormValue("withMustard") //set to true code omitted ///}func prepareOrder(){ code omitted// fmt.Println(withKetchup, withMustard) //both are false even though initially set to true if withKetchup == true && withMustard == true{ }else { }}
1 回答
慕容3067478
TA贡献1773条经验 获得超3个赞
编码
withKetchup := r.FormValue("withKetchup")
使用短变量声明声明并设置字符串类型的局部变量。要设置全局 bool 变量,请通过删除“:”将语句转换为赋值。此外,通过将表单值与 "" 进行比较来计算 bool 值:
withKetchup = r.FormValue("withKetchup") == "true"
因为服务器并发执行处理程序,所以使用这样的全局变量是不安全的。我建议将值作为参数传递给 prepareOrder:
func orderProcess(w http.ResponseWriter, r *http.Request){
r.ParseForm()
withKetchup := r.FormValue("withKetchup") == "true"
withMustard := r.FormValue("withMustard") == "true"
prepareOrder(withKetchup, withMustard)
}
func prepareOrder(withKetchup, withMustard bool){
if withKetchup == true && withMustard == true{
}else {
}
}
- 1 回答
- 0 关注
- 269 浏览
添加回答
举报
0/150
提交
取消