英文:
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?
答案1
得分: 11
你正在处理两个不同的Reader
:
- strings.NewReader() 返回一个
strings.Reader
,它不是一个接口。
但是由于它实现了io.Reader
,你可以将它传递给proxy()
。 proxy()
接受一个io.Reader
,它是一个接口。
对于非接口类型,动态类型始终是静态类型。
type assertion 仅适用于接口,接口可以具有任意的底层类型。
(参见我在接口上的回答,以及“Go:命名类型断言和转换”)
英文:
You are dealing with two different Reader
:
- strings.NewReader() returns a
strings.Reader
, which isn't an interface.
But since it implementsio.Reader
, you can pass it toproxy()
. proxy()
takes anio.Reader
, which is an interface.
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")
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论