为什么类型断言在某些情况下有效,而在另一些情况下无效?

huangapple go评论84阅读模式
英文:

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

问题

这是有问题的源代码:

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
}

有人能告诉我为什么这段代码不能工作吗?

错误发生在这里:

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

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

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

然而,proxy(body io.Reader) 做了同样的事情,但没有错误。为什么?

英文:

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

答案1

得分: 11

你正在处理两个不同的Reader

对于非接口类型,动态类型始终是静态类型。
type assertion 仅适用于接口,接口可以具有任意的底层类型。
(参见我在接口上的回答,以及“Go:命名类型断言和转换”)

英文:

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")

huangapple
  • 本文由 发表于 2014年6月4日 15:10:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/24031205.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定