what does filepath.Base do in golang

huangapple go评论67阅读模式
英文:

what does filepath.Base do in golang

问题

我正在查看这段代码:

if len(os.Args) == 1 {
        fmt.Printf("usage: %s <whole-number>\n", filepath.Base(os.Args[0]))
        os.Exit(1)
    }

我理解它的作用。os.Args 是参数列表。程序应该从命令行调用,所以它检查给定的参数是否超过 1(第一个参数 os.Args[0] 是程序自身的名称),如果没有超过,它会退出程序并打印一个信息性的错误。

然而,我不太理解这部分 filepath.Base(os.Args[0])filepath.Base 返回文件路径的基本部分(即文件名)。但是 os.Args[0] 已经包含了名称,为什么还需要这个额外的步骤,它是必要的吗?

英文:

I am looking at this snippet of code:

if len(os.Args) == 1 {
        fmt.Printf(&quot;usage: %s &lt;whole-number&gt;\n&quot;, filepath.Base(os.Args[0]))
        os.Exit(1)
    }

I understand what it does. os.Args is the list of the arguments. The program is supposed to be invoked from the command line, so it checks to see if the arguments given exceeds 1 (The first one being os.Args[0] is the program's name itself) and if it doesn't, it exits the program and prints an informative error.

However I don't really get this part filepath.Base(os.Args[0]). filepath.Base returns the base of a filepath (namely, its file name). But doesn't os.Args[0] already contain the name? So what this extra step does and why is it necessary?

答案1

得分: 1

filepath.Base 返回提供的字符串的最后一个路径元素。os.Args[0] 可能是单个二进制文件的名称、相对路径或完全限定路径。这只是一种规范化的方式。

英文:

filepath.Base returns the last path element of the provided string. os.Args[0] may be a single binary's name, a relative path, or a fully qualified path. This is simply a way to normalize that.

huangapple
  • 本文由 发表于 2014年12月22日 22:24:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/27604577.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定