【发布时间】:2016-12-27 14:57:07
【问题描述】:
试着写一点go,我想在Golang中创建一个cat函数:
package main
import (
"fmt"
"os"
"io/ioutil"
"log"
)
func main() {
// part to ask the question and get the input
fmt.Print("Which file would you like to read?: ")
var input string
fmt.Scanln(&input)
fmt.Print(input)
// part to give the output
f, err := os.Open(os.Args[1]) // Open the file
if err != nil {
log.Fatalln("my program broken")
}
defer f.Close() // Always close things open
bs, err := ioutil.ReadAll(f)
if err != nil {
log.Fatalln("my program broken")
}
// part to print the output
fmt.Printf("input", bs) // %s convert directly in string the result
}
但我在执行时感到恐慌并且找不到更明确的信息。
我做错了什么?
如何从终端获取有关该错误的更多信息?
$ go run gocat.go 你想读哪个文件?:gocat.go gocat.gopanic:运行时错误:索引超出范围
goroutine 1 [运行]: 恐慌(0x4b1840, 0xc42000a0e0) /usr/lib/go/src/runtime/panic.go:500 +0x1a1 main.main() /home/user/git/go-experimentations/gocat/gocat.go:23 +0x4ba 退出 状态 2
【问题讨论】:
-
os.Args保存在命令行中传递给程序的内容。您应该打算打开一个文件,该文件的名称由用户交互式输入,并最终出现在名为“input”的变量中。您为什么不尝试将其用作要输入的文件名? -
请求用户
-
呃....什么?我无法理解这一点。
-
哦,对不起,我刚刚明白你的意思-_-'