Search code examples
gotypescompilationassert

invalid type assertion: cannot convert os.Stdout to interface type io.ReadWriter?


I'm refering to gopl sample code as below:

v := os.Stdout
v2 = v.(io.ReadWriter)

But go 1.13 will a report compilation error on it:

invalid type assertion: v.(io.ReadWriter) (non-interface type *os.File on left)

I supposed that as long as Stdout is a writer, this conversion to ReadWriter should trigger a runtime type conversion error, but in fact, a compilation error is reported.

I wish to know in what conditions, type assertion/conversion will fail in compile time, and under what condition it will fail in runtime?


Solution

  • You can use io.ReadWriter(os.Stdout) to do that as you already have an concrete pointer to a struct (alternatively also works with structs).

    Type assertions such as v.(*SomeConcreteType) are used when v implements some interface and you want to convert it to a concrete type (struct/pointer...). You're trying to do it the other way around, which is why the compiler complains about the non-interface type.

    That does not really make sense as the only thing you're doing is limiting the methods you can call on v2. You can still pass v to a method that accepts a io.ReadWriter without converting anything as it implements that interface.