*os.File satisfies io.Writer, but []*os.File doesn't satisfy []io.Writer

1,178 views
Skip to first unread message

rando...@gmail.com

unread,
Mar 28, 2012, 6:09:30 AM3/28/12
to golan...@googlegroups.com
Basically I would like to know if there is any way to skip the conversion at below line 19, marked with the comment "### question ###"

package main

import "fmt"
import "io"
import "log"
import "os"

func main() {
   fr, err := os.Open("orig.txt")
   if err != nil {
      log.Fatalln(err)
   }
   fws, err := createFiles()
   if err != nil {
      log.Fatalln(err)
   }
   defer closeFiles(fws)
   ws := make([]io.Writer, len(fws))
   // ### question ### Is it possible to skip this step?
   for i := 0; i < len(fws); i++ {
      ws[i] = fws[i]
   }
   err = doStuff(fr, ws)
   if err != nil {
      log.Fatalln(err)
   }
}

func doStuff(r io.Reader, ws []io.Writer) (err error) {
   // Split the contents of r into the different io.Writers based on an
   // algorithm that has no implication for this example. Below is a
   // placeholder.
   for _, w := range ws {
      _, err = io.CopyN(w, r, 1)
      if err != nil {
         return err
      }
   }
   return nil
}

func createFiles() (fws []*os.File, err error) {
   for i := 0; i < 10; i++ {
      f, err := os.Create(fmt.Sprintf("file_%04d.txt", i))
      if err != nil {
         return nil, err
      }
      fws = append(fws, f)
   }
   return fws, nil
}

func closeFiles(fws []*os.File) {
   for _, f := range fws {
      f.Close()
   }
}

cheers /u

Brad Fitzpatrick

unread,
Mar 28, 2012, 10:44:21 AM3/28/12
to rando...@gmail.com, golan...@googlegroups.com
No, the language doesn't permit that.

But if that copy is expensive or generates too much garbage, you can always wrap that []*os.File slice in another type that implements an interface with methods Len() and Writer(n int) io.Writer which your function doStuff could take, rather than an []io.Writer.

Alexander Sychev

unread,
Mar 28, 2012, 10:58:20 AM3/28/12
to rando...@gmail.com, golan...@googlegroups.com
Hi,

http://play.golang.org/p/BICBf0iQdz
Best regards,
  santucco
Reply all
Reply to author
Forward
0 new messages