dirname equivalent in Go

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

dirname equivalent in Go

问题

我正在学习Go语言,我不知道是否有遗漏的地方,但在搜索后,我想知道:在Go语言中,是否有类似Node.js中的dirname的功能?如何在Go代码中获取当前目录,还是我需要自己实现一个?

英文:

I'm studying Go, I don't know if I missed something, but after searching, I wonder: Does dirname in NodeJS have an equivalent in Go? How to get current directory in Go code, or I have to implement one?

答案1

得分: 9

在Go语言中,你可以使用os.Getwd函数来获取当前目录的绝对路径名。

dir, err := os.Getwd()
if err != nil {
    fmt.Errorf("目录 %v 不存在", err)
}
英文:

In Go you can use os.Getwd which returns a rooted path name corresponding to the current directory.

dir, err := os.Getwd()
if err != nil {
	fmt.Errorf("Dir %v does not exists", err)
}

答案2

得分: 1

我正在同时学习V和Golang,显然,有一个名为os.Executable()的函数可以获得最接近__dirname的等效功能。根据这个来源,你可以运行os.Executable()函数来获取代码运行的目录,然后使用filepath.Dir()来获取只包含绝对路径而不包含可执行文件名称的路径。

我刚刚从参考资料中复制粘贴了这段代码片段,这是在Go中获取__dirname的方法:

package main

import (
	"fmt"
	"os"
	"path/filepath"
)

func main() {
	// 获取启动当前进程的可执行文件的路径名
	pathExecutable, err := os.Executable()
	if err != nil {
		panic(err)
	}
	// 获取目录路径/名称
	dirPathExecutable := filepath.Dir(pathExecutable)

	fmt.Println("当前运行文件的目录...")
	fmt.Println(dirPathExecutable)
}

我同意,这与之前的答案有所不同。在V中也是类似的工作方式,它总是从你运行代码的当前工作目录获取。因此,如果你在家目录中运行os.Getwd(),它将打印出家目录而不是你执行代码的位置。

英文:

I'm studying V and Golang at the same time, and apparently, there's a function called os.Executable() to have the closest __dirname equivalent. According to this source, you run the os.Executable() function to get the directory of where the code is running from, and then do filepath.Dir() to get only the absolute path without the executable's name.

I just copy-pasted this snippet from the reference, but this is how you get the __dirname in Go:

package main

import (
	"fmt"
	"os"
	"path/filepath"
)

func main() {
	// Getting the path name for the executable
	// that started the current process.
	pathExecutable, err := os.Executable()
	if err != nil {
		panic(err)
	}
	// Getting the directory path/name
	dirPathExecutable := filepath.Dir(pathExecutable)

	fmt.Println("Directory of the currently running file...")
	fmt.Println(dirPathExecutable)
}

And I agree, there's a difference between what the previous answer did. It also works similarly in V, where it would always get the current working directory from where you ran the code. So if you are in your home directory, when running os.Getwd(), it will print out the home directory rather than where you executed the code.

huangapple
  • 本文由 发表于 2016年3月2日 16:27:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/35741934.html
匿名

发表评论

匿名网友

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

确定