dongwusang0314 2014-07-14 16:51
浏览 140
已采纳

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

Could someone please explain why this line of code:

var file_list []string = filepath.Glob(os.Getwd() + "/*.*")

Is generating these errors:

multiple-value os.Getwd() in single-value context
multiple-value filepath.Glob() in single-value context

Thank you! Bryan

  • 写回答

1条回答 默认 最新

  • dqy92287 2014-07-14 16:54
    关注

    Both are returning error, so you can't assign them directly.

    func Glob(pattern string) (matches []string, err error)
    func Getwd() (dir string, err error)
    

    You need to, at minimum, ignore the error return value.

    var file_list []string, _ = filepath.Glob(x)
    

    With:

    cwd, _ = os.Getwd()
    x := cwd + "/*.*"
    

    But the best practice would be to check the error and act if it isn't nil.

    Actually, twotwotwo adds in the comments:

    Don't ignore err, though, or someday your program won't do what it should and you won't know why.
    Many times, you want your function to return errors as well and the "default" handler you want is

    if err != nil { return err }
    

    If an error is completely unexpected and the best thing your program can do is quit after encountering it, then:

    if err != nil { log.Panic("error doing foo: ", err) }. 
    

    I recommend github.com/kisielk/errcheck to catch mistakes, which are easy to make early on even when you're trying to be meticulous.


    If you really wanted to use the first of the two returned values, without introducing an intermediate variable, you would need an helper function:

    func slice(args ...interface{}) []interface{} {
        return args
    }
    

    But that wouldn't help much in your case, since []interface is not a []string.


    Another helper function is mentioned by topskip in the comments:

    One can also use the pattern:

    oneArg := must(twoArgsFunc(...)) 
    

    with a helper function 'must' that would panic otherwise, such as text/template/#Must

    func Must(t *Template, err error) *Template
    

    Must is a helper that wraps a call to a function returning (*Template, error) and panics if the error is non-nil.
    It is intended for use in variable initializations such as:

    var t = template.Must(template.New("name").Parse("text"))
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 DS18B20内部ADC模数转换器
  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动