26

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
roadrunner66
  • 7,772
  • 4
  • 32
  • 38
Alishan Khan
  • 522
  • 1
  • 4
  • 13

1 Answers1

46

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)
    }
}
Kaedys
  • 9,600
  • 1
  • 33
  • 40
Simone Carletti
  • 173,507
  • 49
  • 363
  • 364
  • 3
    For the pointer example, alternatively you can set the value the pointer points to using the dereference operator `*`: https://play.golang.org/p/9TrwjUkr4I – Kaedys Jul 21 '16 at 20:41
  • 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" ? – Ran Feldesh May 03 '21 at 12:41