Check empty float or integer value in golang
Asked Answered
V

1

28

I'm trying to check if my integer or float value is empty. But type error is thrown.

Tried:

if foo == nil    
//Error: cannot convert nil to type float32
//all other methods I Tried also throw type errors too
Vivianne answered 21/7, 2016 at 18:13 Comment(5)
What do you mean integer or float value? You can't have it be both.Lietuva
an integer or float cannot be nil. Default value is 0Alasdair
that why I specified or in betweenVivianne
hmm. thats a issue for me now. I should ask this question in qor github issue.Vivianne
thanks for your time guysVivianne
N
49

The zero values for integer and floats is 0. nil is not a valid integer or float value.

A pointer to an integer or a float can be nil, but not its value.

This means you either check for the zero value:

if foo == 0 {
  // it's a zero value
}

Or you deal with pointers:

package main

import (
    "fmt"
)

func main() {
    var intPointer *int

    // To set the value use:
    // intValue := 3
    // intPointer = &intValue

    if intPointer == nil {
        fmt.Println("The variable is nil")
    } else {
        fmt.Printf("The variable is set to %v\n", *intPointer)
    }
}
Narcotism answered 21/7, 2016 at 18:57 Comment(2)
For the pointer example, alternatively you can set the value the pointer points to using the dereference operator *: play.golang.org/p/9TrwjUkr4ISatirist
Thank you @Simone Carletti , is there a GoLang manual reference "The zero values for integer and floats is 0. nil is not a valid integer or float value" ?Saith

© 2022 - 2024 — McMap. All rights reserved.