Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Golang error i is not a type

Tags:

go

I have a simple function which takes a variable gets its type and processes it in to a switch but i get an error :

i is not a type

My code looks like this:

var whatAmI = func(i, interface{}) { // error is here
    switch t := i.(type) {
    case bool:
        fmt.Println("I'm a bool!")
    case int:
        fmt.Println("I'm an int!")
    default:
        fmt.Println("Don't know type %T\n", t)
    }
}
whatAmI(true)
whatAmI(1)
whatAmI("hey")

Am i misunderstanding something here?

like image 750
Sir Avatar asked Dec 19 '22 03:12

Sir


1 Answers

Remove the comma from the function signature and it will work. Try it here.

package main

import (
    "fmt"
)

func main() {
    var whatAmI = func(i interface{}) { // error is here
        switch t := i.(type) {
        case bool:
            fmt.Println("I'm a bool!")
        case int:
            fmt.Println("I'm an int!")
        default:
            fmt.Printf("Don't know type %T\n", t)
        }
    }
    whatAmI(true)
    whatAmI(1)
    whatAmI("hey")

}

Also you were formatting the default case print statement incorrectly, so I changed it to match your expected behavior.

like image 79
Jack Avatar answered Jan 11 '23 16:01

Jack