英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论