正确输入但在golang输出时出现恐慌

时间:2016-12-27 14:57:08

标签: go panic

尝试写一下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 [running]:恐慌(0x4b1840,0xc42000a0e0)   /usr/lib/go/src/runtime/panic.go:500 + 0x1a1 main.main()   /home/user/git/go-experimentations/gocat/gocat.go:23 + 0x4ba退出   状态2

3 个答案:

答案 0 :(得分:3)

我想你在网上发现了一些例子,并不太明白发生了什么。

来自os包的文档。

  

Args持有命令行参数,从程序名称开始。

由于您在没有任何参数的情况下启动了程序并且os.Args是一个切片,因此当您访问切片的边界时,程序会发生混乱。 (就像试图访问任何不存在的数组的元素一样)

看起来你正试图在这里提示输入

var input string
fmt.Scanln(&input)
fmt.Print(input)

您需要做的就是替换

f, err := os.Open(os.Args[1])

使用:

f, err := os.Open(input)

您上次的打印声明也不正确。

应该是:

// part to print the output
fmt.Printf("input \n %s", string(bs))

您需要将当前为bs的{​​{1}}投放到[]byte,然后您需要添加string以向%s表明fmt.Printf应该放在格式字符串

答案 1 :(得分:1)

os.Open(os.Args[1])Args[1]超出范围。你应该打开你输入的文件:

f, err := os.Open(input)

答案 2 :(得分:1)

您使用=而不是:= 所以这是你的错误来自哪里。