Checking for Empty Integer in Golang

huangapple go评论74阅读模式
英文:

Checking for Empty Integer in Golang

问题

我正在设计一个API,用户发送整数值,根据发送的值执行某些操作。在验证检查中,我必须将该值与0进行比较,即if intValue == 0

然而,如果值为0,我还必须执行不同的操作。有没有办法在不将其与0进行比较的情况下检查整数是否不存在或为空?

> **注意:**要求由客户端设置,我无法更改它们。

英文:

I am designing an API where a user sends integer values and some operation is performed depending on the value sent. During the validation check that whether this value exists in the request, I have to equate it to 0 i.e. 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?

> Note: The requirements are set by the client and I cannot change them.

答案1

得分: 1

当将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 {
    // JSON数据中未定义OptionalValue
} else {
    // OptionalValue已定义,但可能为0
    val := *data.OptionalValue
}
英文:

When decoding JSON data into a struct, you can differentiate optional fields by declaring them as a pointer type.

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
}

答案2

得分: 0

如果考虑兼容性,我的建议是使用json.Number。这样,请求方可以传递int和string,并且还可以确定请求方是否传递了参数。

例如:

package main

import (
	"encoding/json"
	"fmt"
	"log"
)

type Param struct {
	Level json.Number `json:"level"`
}

func main() {
	var p Param

	if err := json.Unmarshal([]byte(`{"level": 30}`), &p); err != nil {
		log.Fatalf("Unmarshal err: %v", err)
	}

	if p.Level == "" {
		log.Fatal("level not pass")
	}

	level, err := p.Level.Int64()
	if err != nil {
		log.Fatalf("level is not integer")
	}

	fmt.Printf("level: %d", level)
}
英文:

If considering compatibility, my suggestion is to use json.Number. This way, both int and string can be passed by the requesting side, and it can also determine whether the requesting side has passed the parameter.

For example:

package main

import (
	"encoding/json"
	"fmt"
	"log"
)

type Param struct {
	Level json.Number `json:"level"`
}

func main() {
	var p Param

	if err := json.Unmarshal([]byte(`{"level": 30}`), &p); err != nil {
		log.Fatalf("Unmarshal err: %v", err)
	}

	if p.Level == "" {
		log.Fatal("level not pass")
	}

	level, err := p.Level.Int64()
	if err != nil {
		log.Fatalf("level is not integer")
	}

	fmt.Printf("level: %d", level)
}

答案3

得分: -2

在生产中 如@phuclv所说

不存在"空整数"这样的东西

不优雅的实现

检查是否为必需项:

例如

@Hymns For Disco 使用json.NewDecoder
或者
validators

但它已被废弃
https://stackoverflow.com/questions/31801257/why-required-and-optional-is-removed-in-protocol-buffers-3

另一种方法:

使用map而不是struct,可以判断字段是否存在

以下是一个示例

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)
}

英文:

in production as @phuclv say

there's no such thing as an "empty integer"

inelegant implementation

check if it is required:

like

@Hymns For Disco use json.NewDecoder
or
validators

but it is being abandoned:
https://stackoverflow.com/questions/31801257/why-required-and-optional-is-removed-in-protocol-buffers-3

another way:

use map but struct,which can tell if a field exists

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)
}

huangapple
  • 本文由 发表于 2022年8月11日 14:33:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/73316233.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定