Check empty float or integer value in golang

Alishan Khan picture Alishan Khan · Jul 21, 2016 · Viewed 40.4k times · Source

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

Answer

Simone Carletti picture Simone Carletti · Jul 21, 2016

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