gpt4 book ai didi

pointers - 在 Golang 中返回文件指针

转载 作者:IT王子 更新时间:2023-10-29 00:43:54 25 4
gpt4 key购买 nike

我仍在努力学习 Golang 的基础知识。

考虑以下示例代码:

func OpenOutputFile(name string) (fp *os.File) {
fp, err := os.Create(name)
if err != nil {
panic(err)
}

defer func() {
if err := fp.Close(); err != nil {
panic(err)
}
}()

return fp
}

我假设调用:

fp := OpenOutputFile("output.txt")

现在将使 fp 成为文件指针 (*os.File),这样我就可以调用如下语句:

io.WriteString(fp, "Hello World")

在另一个函数中。但是在调用这个方法的时候,产生了错误:

0 write output.txt: bad file descriptor

所以看起来返回的指针是无效的。如何返回一个格式正确的指针以与 io.WriteString 一起使用?

感谢您的帮助!

注意:当创建文件指针和写入文件指针存在于同一个方法中时,一切都会按预期执行。将逻辑分解为一个函数会导致它无法按预期运行。

最佳答案

The Go Programming Language Specification

Defer statements

A "defer" statement invokes a function whose execution is deferred to the moment the surrounding function returns, either because the surrounding function executed a return statement, reached the end of its function body, or because the corresponding goroutine is panicking.

Each time a "defer" statement executes, the function value and parameters to the call are evaluated as usual and saved anew but the actual function is not invoked. Instead, deferred functions are invoked immediately before the surrounding function returns, in the reverse order they were deferred. If a deferred function value evaluates to nil, execution panics when the function is invoked, not when the "defer" statement is executed.

For instance, if the deferred function is a function literal and the surrounding function has named result parameters that are in scope within the literal, the deferred function may access and modify the result parameters before they are returned. If the deferred function has any return values, they are discarded when the function completes.

func OpenOutputFile(name string) (fp *os.File) {
fp, err := os.Create(name)
if err != nil {
panic(err)
}

defer func() {
if err := fp.Close(); err != nil {
panic(err)
}
}()

return fp
}

你打开文件

fp, err := os.Create(name)

你关闭文件

err := fp.Close()

关闭后,fp 不再指向有效的文件描述符。

关于pointers - 在 Golang 中返回文件指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36109887/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com