在Golang中设置绝对文件路径。

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

Setting up absolute file path in Golang

问题

我是一个提供从文件中读取的虚拟数据集合的包的翻译助手。

代码如下:

func GetArrayOfSize(n int) []int {
    f, _ := os.Open("./arrays.txt")
    defer f.Close()

    numbers := make([]int, 0)
    scanner := bufio.NewScanner(f)

    for scanner.Scan() {
        s, _ := strconv.Atoi(scanner.Text())
        numbers = append(numbers, s)
    }

    return numbers[0:n]
}

当我在这个包内测试时,它运行得很好,但是当我从另一个包中调用GetArrayOfSize时,会出现运行时错误:

panic: runtime error: slice bounds out of range [recovered]
    panic: runtime error: slice bounds out of range

我猜测这个错误是由于相对路径'./arrays.txt'引起的。我该如何获取我的dummy包的绝对路径来修复这个问题?

非常感谢!

英文:

I am a package whose only role is to provide a collection of dummy data read from files.

It looks like this:

func GetArrayOfSize(n int) []int {
f, _ := os.Open("./arrays.txt")
defer f.Close()

numbers := make([]int, 0)
scanner := bufio.NewScanner(f)

for scanner.Scan() {
	s, _ := strconv.Atoi(scanner.Text())
	numbers = append(numbers, s)
}

	return numbers[0:n]
}

It works fine when I test it inside this package however whenever I call GetArrayOfSize from another package I get a runtime error:

panic: runtime error: slice bounds out of range [recovered]
    panic: runtime error: slice bounds out of range

I am guessing this error is due to the relative path: './arrays.txt. How can I fetch the absolute path of my dummy package to fix this?

Many thanks

答案1

得分: 1

你应该检查从os.Open返回的错误并进行处理。

你可以使用go/build包获取源代码目录的绝对路径:

p, err := build.Default.Import("github.com/user/repo/dummy", "", build.FindOnly)
if err != nil {
    // 处理错误
}
fname := filepath.Join(p.Dir, "arrays.txt")

这段代码假设GOPATH环境变量已设置。

英文:

You should check the error return from os.Open and handle it.

You can get the absolute path to the source code directory using the go/build package:

p, err := build.Default.Import("github.com/user/repo/dummy", "", build.FindOnly)
if err != nil {
	// handle error
}
fname := filepath.Join(p.Dir, "arrays.txt")

This code assumes that the GOPATH environment variable is set.

答案2

得分: 0

使用go工具运行install命令,你就可以在系统的任何位置运行你的命令了。这里有一个很好的链接,提供了install命令的示例:如何编写Go代码

英文:

Run the install command with the go tool and you should be able to run your command from anywhere on your system. Here's a good link that gives an example of the install command: How To Write Go Code

huangapple
  • 本文由 发表于 2015年1月31日 02:32:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/28242430.html
匿名

发表评论

匿名网友

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

确定