在我的golang应用程序中,我根据表单输入将一些全局变量设置为true,然后在后续函数中使用时发现它们已更改为false。问题,在golang中声明和设置布尔值的正确方法是什么?
var withKetchup bool
var withMustard bool
func 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 {
}
}
答案 0 :(得分:6)
代码
withKetchup := r.FormValue("withKetchup")
使用short variable declaration声明并设置string类型的局部变量。要设置全局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 {
}
}