On Thu, 13 Oct 2016 10:38:16 -0700 (PDT)
d...@veryhaha.com wrote:

> https://golang.org/ref/spec#Type_assertions
>  var x interface{} = 7  // x has dynamic type int and value 7
>  i := x.(int)           // i has type int and value 7
>  type I interface { m() }
>  var y I
>  // illegal: string does not implement I (missing method m)
>  s := y.(string)
>  // r has type io.Reader and y must implement both I and io.Reader
>  r := y.(io.Reader)
> > sorry, my mistake, if the underlying value doesn't implement
> > io.Reader, the last line will panic.
> but it compiles even if the underlying value doesn't implement
> io.Reader, not like the " s := y.(string) ", which doesn't compile.

The difference is that "string" is a concrete type while io.Reader is
an interface, and y is an interface as well.

Let's explain it piecemeal.

First, consider "y.(string)".
Since "string" is a concrete type and any value contained in the
variable "y" must implement the interface "I" -- a rule which the
compiler enforces, -- the compiler trivially proves that no value
possibly contained in "y" can ever be of type string because that type
does not implement "I" -- by having no method matching "m()".

Second, consider "y.(io.Reader)".
Since io.Reader is itself an interface, the "y" variable can contain
values of an unbounded set of types which both implement "I" and
io.Reader at the same time.

The crucial bit here is that implementation of interfaces in Go is
implicit and is figured out at runtime.

You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to