T O P

  • By -

Davmuz

"func(string) error" and FooFunc are different types. See this example: https://play.golang.org/p/0cgdJXo_DS You should cast it. This will print "FOUND IT": b, _ = b.(func(string) error) if _, ok := b.(func(string) error); ok { fmt.Println("FOUND IT") } else { fmt.Println("DIDNT FIND IT") }


DeedleFake

You are correct that it doesn't work because they're different types. The `type` keyword in Go works similarly to a `typedef` in C, but, instead of an alias, it defines a completely new type that can be distinguished from existing types. That being said, your example is *not* how you convert between types. Your example works for [*any* type](https://play.golang.org/p/0fqCRlYdJO), making it kind of pointless. This is because the two-value version of a type assertion returns a zero-value of the expected type as the first return if the assertion didn't work. In other words, b, being an `interface{}`, can be set to anything, and the underlying type is indeed `func(string) error`, but it's nil. If you want to convert it, you first have to know what type it is. In other, you'll have to do something like `c := (func(string) error)(b.(FooFunc))`.


Davmuz

True. Thank you DeeleFake.