Issues casting interface{} to func type alias

49 views
Skip to first unread message

Mitchell Hashimoto

unread,
Jul 30, 2013, 8:50:10 PM7/30/13
to golang-nuts
See this Go Play example, which explains it best (and succinctly):
http://play.golang.org/p/Vh6-74pDeJ

Does this seem to be working as intended? Seems odd to me that this
doesn't work.

Best,
Mitchell

Nigel Tao

unread,
Jul 30, 2013, 9:04:54 PM7/30/13
to Mitchell Hashimoto, golang-nuts
On Wed, Jul 31, 2013 at 10:50 AM, Mitchell Hashimoto
<mitchell....@gmail.com> wrote:
> See this Go Play example, which explains it best (and succinctly):
> http://play.golang.org/p/Vh6-74pDeJ
>
> Does this seem to be working as intended?

It's working as intended. When you say
type FooFunc func() error
The "FooFunc" type is a separate type to the "func() error" type. The
first type is named (the name is "FooFunc"), the second type is
unnamed.

When you say
var raw interface{} = foo
foo has type "func() error" and then raw's dynamic type is also "func() error".

The reason that runFoo(foo) works even though runFoo takes a "FooFunc"
and foo has type "func() error" is because "A value x is assignable to
a variable of type T if... x's type V and T have identical underlying
types and at least one of V or T is not a named type." So says
http://golang.org/ref/spec#Assignments

Nigel Tao

unread,
Jul 30, 2013, 9:05:41 PM7/30/13
to Mitchell Hashimoto, golang-nuts
I forgot to add that you can replace
var raw interface{} = foo
with
var raw interface{} = FooFunc(foo)
Reply all
Reply to author
Forward
0 new messages