doupo2157 2013-12-16 01:30
浏览 869
已采纳

[] byte或文件中的io.WriteSeeker和io.ReadSeeker

I have a method called "DoSomething". DoSomething will take binary source data perform an operation on it, and write out binary data. DoSomething needs to be generic enough to handle either a []byte array or a file handle for both the source and destination. To accomplish this, I have attempted to declare the method like this:

func DoSomething(source *io.ReadSeeker, destination *io.WriteSeeker)

I have implemented the ReadSeeker and WriteSeeker for working with buffers, using my own custom, required methods (if there is a way to automatically accomplish this, I'd love to hear about it as well). Unfortunately, I can't seem to figure out how to create either an io.ReadSeeker or io.WriteSeeker from a file handle. I'm fairly sure there must be some pre-cooked way of handling this without having to manually implement them. Is this possible?

  • 写回答

2条回答 默认 最新

  • douran6443 2013-12-16 01:44
    关注

    A file already implements both of those. You can do something like this:

    package main
    
    import (
       "fmt"
       "io"
       "os"
    )
    
    func main() {
       f, err := os.Open("test.txt")
       if err != nil {
         fmt.Println(err)
       }
       defer f.Close()
       f2, err := os.Create("test2.txt")
       if err != nil {
          fmt.Println(err)
       }
       defer f2.Close()
       DoSomething(f, f2) 
    }
    
    func DoSomething(source io.ReadSeeker, destination io.WriteSeeker) {
       io.Copy(destination, source)
    }
    

    Also, you don't need to pass pointers to interfaces, which makes it easier to deal with them.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog