dongtangyi8962 2014-06-04 07:10
浏览 118
已采纳

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

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条回答 默认 最新

  • douqiang7462 2014-06-04 07:15
    关注

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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料