douhuang5331 2013-06-14 09:29
浏览 38
已采纳

此类型断言曾经有效吗?

I am reading the source code for Go's io package and I came across a snippet I don't fully understand. Here it is

func WriteString(w Writer, s string) (n int, err error) {
    if sw, ok := w.(stringWriter); ok {
        return sw.WriteString(s)
    }
    return w.Write([]byte(s))
}

where

type stringWriter interface {
    WriteString(s string) (n int, err error)
}

type Writer interface {
    Write(p []byte) (n int, err error)
}

The type assertion w.(stringWriter) asserts that the dynamic type of w (i.e. Writer) implements the stringWriter interface. I don't see how this is possible given the type definitions of stringWriter and Writer. Assuming that this code is correct, what is it that I am missing?

  • 写回答

1条回答 默认 最新

  • douweida2878 2013-06-14 10:14
    关注

    You can easily build a type which implements Writer as well as stringWriter:

    type StringWriter struct{}
    
    func (s StringWriter) Write(in []byte) (int, error) { 
        return 0, nil 
    }
    func (s StringWriter) WriteString(s string) (int, error) { 
        return s.Write([]byte(s)) 
    }
    

    So passing an instance of StringWriter to io.WriteString results in StringWriter.WriteString being called.

    The logic behind io.WriteString is: Use WriteString on the writer if it has such a method or fall back to string to []byte conversion otherwise. To test whether the instance implements a method or not, interfaces are used, as these are just method sets and can be tested for easily.

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

报告相同问题?

悬赏问题

  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100