1

in one of my golang Projects i went to mock the os.FileInfo for testcases.

I am not sure if I understand the interface handling of golang correctly. As far as I know the following piece of code should work, but I get an Compilererror saying that the interface does not match.

I modified this go-doc example a bit in case you want to test it out yourself.

package main

import (
    "fmt"
    "io/ioutil"
    "log"
)

type file interface{
    Name() string
} 

func readFiles() []file{
    files, err := ioutil.ReadDir(".")

    if err != nil {
        log.Fatal(err)
    }

    return files
}

func main() {
    files := readFiles()

    for _, file := range files {
        fmt.Println(file.Name())
    }
}

Following at the golang doc, the ioutil.ReadDir(".") should Return a slice of os.FileInfo which should be a specialisation of my selfwritten file interface.

Can anyone help me out of this hell of misconceptions and entanglements, please?

Thank you very much guys!

J Polack
  • 118
  • 1
  • 1
  • 5

2 Answers2

0

os.FileInfo is interface and it can converted to file. But you try to convert []os.FileInfo to []file. Slice is not interface, and can not be asserted.

David S
  • 19
  • 4
0

To elaborate on the other answer and comments, os.FileInfo does fulfill the file interface you've defined, but a slice of os.FileInfo does not implicitly convert to a slice of your file interface. A simple fix would be to have your readFiles do the conversion explicitly, e.g.

func readFiles() []file{
    fileInfos, err := ioutil.ReadDir(".")

    if err != nil {
        log.Fatal(err)
    }

    files := make([]file, len(fileInfos))
    for i, fi := range fileInfos {
        files[i] = fi
    }

    return files
}
Matt
  • 330
  • 5
  • 8