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

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

报告相同问题?

悬赏问题

  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教