V
V
Vadim Rublev2021-08-24 18:56:52
go
Vadim Rublev, 2021-08-24 18:56:52

How to cast os.FileInfo type to string type?

How to cast os.FileInfo type to string type? What is there in os.FileInfo, besides the elements in the slice ?
In particular, I want to leave only files of a certain type in the slice of elements in the folder :

filesDir, err := ioutil.ReadDir(".")
for _, fileDir := range filesDir {
    if filepath.Ext(string(fileDir)) == ".txt" && !fileDir.IsDir() {
        fmt.Println("Файл(ы) .txt в текущей папке:", fileDir.Name())
    }
}

In general, does each surrogate type need its own method of casting to another type? Or is there some universal approach?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
Evgeny Mamonov, 2021-08-24
@Vadim Rublev

ioutil.ReadDir returns [] fs.FileInfo
This is an interface, looks like this

type FileInfo interface {
  Name() string       // base name of the file
  Size() int64        // length in bytes for regular files; system-dependent for others
  Mode() FileMode     // file mode bits
  ModTime() time.Time // modification time
  IsDir() bool        // abbreviation for Mode().IsDir()
  Sys() interface{}   // underlying data source (can return nil)
}

Those. in your case filepath.Ext(string(fileDir)) can be replaced by filepath.Ext(fileDir.Name())
Is that what you need or do you need something else?
From the code example, it's not entirely clear why you need to cast to os.FileInfo/string.
Looked os.FileInfo
It is defined as type FileInfo = fs.FileInfo
Ie . Roughly, this is the same interface, whose methods can be called in exactly the same way.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question