24hours
24hours

Reputation: 191

Why a type assertion works in one case, not in another?

Here is the problematic source code:

http://play.golang.org/p/lcN4Osdkgs

package main
import(
    "net/url"
    "io"
    "strings"
) 

func main(){
    v := url.Values{"key": {"Value"}, "id": {"123"}}
    body := strings.NewReader(v.Encode())
    _ = proxy(body)
    // this work 

    //invalid type assertion: body.(io.ReadCloser) (non-interface type *strings.Reader on left)
    _, _ = body.(io.ReadCloser)

}

func proxy( body io.Reader) error{
    _, _ = body.(io.ReadCloser)
    return  nil
}

Can someone tell me why this code wont work ?

The error occur here:

body := strings.NewReader(v.Encode())

rc, ok := body.(io.ReadCloser)

// invalid type assertion: body.(io.ReadCloser) (non-interface type *strings.Reader on left)

However proxy(body io.Reader) do the same thing but have no error. Why?

http://play.golang.org/p/CWd-zMlrAZ

Upvotes: 4

Views: 2738

Answers (1)

VonC
VonC

Reputation: 1328292

You are dealing with two different Reader:

For non-interface types, the dynamic type is always the static type.
A type assertion works for interfaces only, which can have arbitrary underlying type.
(see my answer on interface, and "Go: Named type assertions and conversions")

Upvotes: 11

Related Questions