Search code examples
gointeger

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. 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.


Solution

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