When will the open file (* os.File) be closed if it is not actively closed?

The

code is as follows:

package main

import (
    "fmt"
    "io"
    "os"
)

func main() {
    f := openFile()
    useFile(f)
    useFile2(f)
}

func openFile() *os.File {
    //hello.txt  world
    f, _ := os.Open("hello.txt")
    return f
}

func useFile(f *os.File) {
    fmt.Println("f")
    io.Copy(os.Stdout, f)
    fmt.Println()
}

func useFile2(f *os.File) {
    fmt.Println("f")
    io.Copy(os.Stdout, f)
    fmt.Println()
}

output:

using f
world
for the first time using f
for the second time

the second time I used f (* os.File), f was already closed, but I didn"t actively close it.
questions are as follows:
when will open files ( os.File) be closed if they are not actively closed? *
if I turn it off automatically after using it once, do I still need to turn it off actively?
ask the bosses to answer my questions

Apr.26,2022

f is not closed by you, but after the first copy, the offset has been moved to the end of the file, so the second copy can not read the content
you can call f.Seek () before the second copy to set the file offset

.
Menu