本文介绍了嵌入式接口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Go对我来说还很新,我很惊讶无法使用嵌入式接口的子类型。
这里是一个小例子来解释我的意思:

pre $ func test(sl bufio.ReadWriter){
//不能在函数参数
readStuff(sl)
[...]
writeStuff(sl)中使用类型为bufio.Reader的sl(类型为bufio.ReadWriter)//同类错误
}

func readStuff(sl bufio.Reader){
[...]
}

由于每个接口都有相同的内存布局,ReadWriter是一个Reader和一个Writer,所以我希望这个代码能够工作。
我尝试将接口类型转换为:

  readStuff(sl。(buffio.Reader))

但它也不起作用。所以我有两个问题:


  • 为什么它不起作用?
  • 他们是不同的类型。但是, bufio.ReadWriter 包含一个指向 bufio.Reader 类型和一个 bufio.Writer 键入为其结构的元素。所以传递正确的应该很容易。试试这个:

      func test(sl bufio.ReadWriter){
    readStuff(sl.Reader)
    [...]
    writeStuff(sl.Writer)
    }

    //将此bufio.Reader更改为指针接收器
    func readStuff(sl * bufio。阅读器){
    [...]
    }


    I'm still quite new to Go and I was surprised to not be able to use the subtype of an embedded interface.Here is a small example to explain what I mean:

    func test(sl bufio.ReadWriter){
        // cannot use sl(type bufio.ReadWriter) as type bufio.Reader in function argument
        readStuff(sl)
        [...]
        writeStuff(sl) // same kind of error
    }
    
    func readStuff(sl bufio.Reader){
        [...]
    }
    

    As every interface have the same memory layout and ReadWriter is a Reader and a Writer, I was expecting this code to work.I did try to convert the interface type with:

    readStuff(sl.(buffio.Reader))
    

    But it doesn't work either. So I've got two questions:

    • Why doesn't it work?
    • What's the go philosophy about that problem?

    解决方案

    They're different types. However, a bufio.ReadWriter contains a pointer to both a bufio.Reader type and a bufio.Writer type as elements of its struct. So passing the correct one should be easy enough. Try this:

    func test(sl bufio.ReadWriter){
        readStuff(sl.Reader)
        [...]
        writeStuff(sl.Writer)
    }
    
    // Changed this bufio.Reader to a pointer receiver
    func readStuff(sl *bufio.Reader) {
        [...]
    }
    

    这篇关于嵌入式接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-13 14:46