Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check empty float or integer value in golang

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
like image 761
Alishan Khan Avatar asked Jul 21 '16 18:07

Alishan Khan


1 Answers

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)
    }
}
like image 159
Simone Carletti Avatar answered Sep 21 '22 01:09

Simone Carletti