-5

I am trying to find if a variable is of type float64:

package main
import ("fmt")
func main() {
    myvar := 12.34
    if myvar.(type) == float64 { 
        fmt.Println("Type is float64.")
    }
}

However, it is not working and giving following error:

./rnFindType.go:6:10: use of .(type) outside type switch
./rnFindType.go:6:21: type float64 is not an expression

What is the problem and how can it be solved?

rnso
  • 23,686
  • 25
  • 112
  • 234
  • 5
    Go is a statically typed language, in your example it cannot be other than `float64` (that's the default type for the floating point constant `12.34` which is used in your short variable declaration). If the value is an interface type, then you may use a [type assertion](https://golang.org/ref/spec#Type_assertions) which would look something like this: `if x, ok := myvar.(float64); ok { fmt.Println("its float64:", x) }` – icza Aug 14 '19 at 14:59
  • 1
    See related: [How to check if interface{} is a slice](https://stackoverflow.com/questions/40343471/how-to-check-if-interface-is-a-slice/40343605#40343605). – icza Aug 14 '19 at 15:04

1 Answers1

3

You know that myvar is a float64 because the variable is declared with the concrete type float64.

If myvar is an interface type, then you can use a type assertion to determine if the concrete value is some type.

var myvar interface{} = 12.34
if _, ok := myvar.(float64); ok {
    fmt.Println("Type is float64.")
}

Try this program at https://play.golang.org/p/n5ftbp5V2Sx

nigma
  • 46
  • 1