Go 错误:“单值上下文中的多值 filepath.Glob()”

Bry*_*een 2 go

有人可以解释为什么这行代码:

var file_list []string = filepath.Glob(os.Getwd() + "/*.*")
Run Code Online (Sandbox Code Playgroud)

正在生成这些错误:

multiple-value os.Getwd() in single-value context
multiple-value filepath.Glob() in single-value context
Run Code Online (Sandbox Code Playgroud)

谢谢!布莱恩

Von*_*onC 5

两者都返回错误,因此您不能直接分配它们。

func Glob(pattern string) (matches []string, err error)
func Getwd() (dir string, err error)
Run Code Online (Sandbox Code Playgroud)

您至少需要忽略错误返回值。

var file_list []string, _ = filepath.Glob(x)
Run Code Online (Sandbox Code Playgroud)

和:

cwd, _ = os.Getwd()
x := cwd + "/*.*"
Run Code Online (Sandbox Code Playgroud)

但最佳做法是检查错误并在错误时采取行动nil

实际上,twotwotwo在评论中添加

err但是,请不要忽略,否则有一天您的程序将不会执行它应该做的事情,而且您将不知道为什么
很多时候,您希望您的函数也返回错误,而您想要的“默认”处理程序是

if err != nil { return err }
Run Code Online (Sandbox Code Playgroud)

如果错误完全出乎意料,并且您的程序能做的最好的事情就是在遇到它后退出,那么:

if err != nil { log.Panic("error doing foo: ", err) }. 
Run Code Online (Sandbox Code Playgroud)

我推荐github.com/kisielk/errcheck来捕捉错误,即使您试图一丝不苟,这些错误也很容易在早期犯下。


如果您真的想使用两个返回值中的第一个,而不引入中间变量,则需要一个辅助函数

func slice(args ...interface{}) []interface{} {
    return args
}
Run Code Online (Sandbox Code Playgroud)

但这对您的情况没有多大帮助,因为[]interface不是[]string.


topskip评论中提到了另一个辅助函数:

还可以使用以下模式:

oneArg := must(twoArgsFunc(...)) 
Run Code Online (Sandbox Code Playgroud)

带有辅助函数“ must”,否则会发生恐慌,例如text/template/#Must

func Must(t *Template, err error) *Template
Run Code Online (Sandbox Code Playgroud)

Must是一个帮助函数,它包装了一个函数的调用,(*Template, error)如果错误非零,则返回和恐慌。
它旨在用于变量初始化,例如:

var t = template.Must(template.New("name").Parse("text"))
Run Code Online (Sandbox Code Playgroud)