[英]Checking for Empty Integer in Golang
I am designing an API where a user sends integer values and some operation is performed depending on the value sent.我正在设计一个 API 用户发送 integer 值并根据发送的值执行一些操作。 During the validation check that whether this value exists in the request, I have to equate it to 0 ie if intValue == 0
.在验证请求中是否存在此值的验证期间,我必须将其等同于 0 即if intValue == 0
。
However, I also have to perform a different operation in case the value is 0. Is there any way I can check that the integer does not exist or is empty without equating to 0?但是,如果值为 0,我还必须执行不同的操作。有什么方法可以检查 integer 不存在或为空而不等于 0?
Note: The requirements are set by the client and I cannot change them.注意:要求由客户设定,我无法更改。
When decoding JSON data into a struct, you can differentiate optional fields by declaring them as a pointer type.在将 JSON 数据解码为结构时,您可以通过将可选字段声明为指针类型来区分它们。
For example:例如:
type requestFormat struct {
AlwaysPresent int
OptionalValue *int
}
Now when the value is decoded, you can check if the value was supplied at all:现在,当值被解码时,您可以检查是否提供了该值:
var data requestFormat
err := json.NewDecoder(request.Body).Decode(&data)
if err != nil { ... }
if data.OptionalValue == nil {
// OptionalValue was not defined in the JSON data
} else {
// OptionalValue was defined, but it still may have been 0
val := *data.OptionalValue
}
in production as @phuclv say正如@phuclv 所说,在生产中
there's no such thing as an "empty integer"没有“空整数”这样的东西
like喜欢
@Hymns For Disco use json.NewDecoder or validators @Hymns 对于迪斯科使用 json.NewDecoder 或验证器
but it is being abandoned : Why required and optional is removed in Protocol Buffers 3但它被放弃了: 为什么在 Protocol Buffers 3 中删除了 required 和 optional
use map but struct,which can tell if a field exists使用 map 但结构,它可以判断一个字段是否存在
follow is a example下面是一个例子
package main
import (
"encoding/json"
"io/ioutil"
"net/http"
)
type Test struct {
Name string
Age int
}
func testJson(w http.ResponseWriter, r *http.Request) {
aMap := make(map[string]interface{})
data, _ := ioutil.ReadAll(r.Body)
json.Unmarshal(data, &aMap)
test := Test{}
json.Unmarshal(data, &test)
}
func main() {
http.HandleFunc("/", testJson)
http.ListenAndServe(":8080", nil)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.