在Go语言中,输入正确但输出错误的情况通常被称为”panic”。

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

Correct on input but panic on output in golang

问题

尝试编写一些Go代码,我想在Golang中创建一种类似于cat函数的功能:

package main

import (
    "fmt"
    "os"
    "io/ioutil"
    "log"
)

func main() {
    // 部分用于询问问题并获取输入
    fmt.Print("您想要读取哪个文件?:")
    var input string
    fmt.Scanln(&input)
    fmt.Print(input)

    // 部分用于输出结果
    f, err := os.Open(input) // 打开文件
    if err != nil {
        log.Fatalln("程序出错")
    }

    defer f.Close() // 始终关闭打开的文件

    bs, err := ioutil.ReadAll(f)
    if err != nil {
        log.Fatalln("程序出错")
    }

    // 部分用于打印输出结果
    fmt.Printf("输入:%s", bs) // %s 将结果直接转换为字符串
}

但是我在执行时遇到了Go的panic,并且没有找到更明确的信息。

我做错了什么?

如何从终端获取有关该错误的更多信息?

$
go run gocat.go 您想要读取哪个文件?:gocat.go
gocat.gopanic: 运行时错误:索引超出范围

goroutine 1 [running]: panic(0x4b1840, 0xc42000a0e0)
/usr/lib/go/src/runtime/panic.go:500 +0x1a1 main.main()
/home/user/git/go-experimentations/gocat/gocat.go:23 +0x4ba exit
状态 2

英文:

Trying to write a bit of go, I would like to create a sort of cat function in Golang:

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                  

}

But I get a go panic on execution and do not find more explicit information.

What I have done wrong?

How can I get more information about that error from the terminal?

> $
> go run gocat.go Which file would you like to read?: gocat.go
> gocat.gopanic: runtime error: index out of range
>
> goroutine 1 [running]: panic(0x4b1840, 0xc42000a0e0)
> /usr/lib/go/src/runtime/panic.go:500 +0x1a1 main.main()
> /home/user/git/go-experimentations/gocat/gocat.go:23 +0x4ba exit
> status 2

答案1

得分: 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)

你最后的打印语句也是不正确的。

应该是:

// 打印输出部分
fmt.Printf("input \n %s", string(bs))

你需要将当前的[]byte类型的bs转换为string类型,并且需要添加%s来指示fmt.Printf在格式字符串中放置string(bs)的位置。

英文:

I imagine you found some examples online and don't quite understand what is going on.

From the os package's documentation.

> Args hold the command-line arguments, starting with the program name.

Since you started your program without any arguments and os.Args is a slice, the program panics when you access out of the slice's bounds. (Like trying to access an element of any array that does not exist)

It looks like you are trying to prompt for the input here

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

All you need to do is replace

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

With:

f, err := os.Open(input)

Your last print statement is also incorrect.

It should be:

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

You need to cast bs which is currently []byte to a string and you need to add %s to indicate to fmt.Printf where string(bs) should be placed in the format string

答案2

得分: 1

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

f, err := os.Open(input)
英文:

not os.Open(os.Args[1]), Args[1] is out of range. you should open the file you input like this:

f, err := os.Open(input)

答案3

得分: 1

你使用的是=而不是:=,所以你的错误就是从这里产生的。

英文:

You use = rather than :=
So here is from where your error comes from.

huangapple
  • 本文由 发表于 2016年12月27日 22:57:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/41347423.html
匿名

发表评论

匿名网友

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

确定