繁体   English   中英

在 Golang 中检查空的 Integer

[英]Checking for Empty Integer in Golang

我正在设计一个 API 用户发送 integer 值并根据发送的值执行一些操作。 在验证请求中是否存在此值的验证期间,我必须将其等同于 0 即if intValue == 0

但是,如果值为 0,我还必须执行不同的操作。有什么方法可以检查 integer 不存在或为空而不等于 0?

注意:要求由客户设定,我无法更改。

在将 JSON 数据解码为结构时,您可以通过将可选字段声明为指针类型来区分它们。

例如:

type requestFormat struct {
    AlwaysPresent int
    OptionalValue *int
}

现在,当值被解码时,您可以检查是否提供了该值:

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
}

正如@phuclv 所说,在生产

没有“空整数”这样的东西

不优雅的实现

检查是否需要:

喜欢

@Hymns 对于迪斯科使用 json.NewDecoder 或验证器

但它被放弃了为什么在 Protocol Buffers 3 中删除了 required 和 optional

另一种方式:

使用 map 但结构,它可以判断一个字段是否存在

下面是一个例子

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM