【问题标题】:Golang: panic: runtime error: invalid memory address or nil pointer dereference using bufio.ScannerGolang:恐慌:运行时错误:无效的内存地址或使用 bufio.Scanner 的 nil 指针取消引用
【发布时间】:2016-12-12 23:14:28
【问题描述】:

我正在实现一个使用 bufio.Scanner 和 bufio.Writer 的 go 程序,我已将我的代码打包如下

package main

import (
    "fmt"
    "player/command"
    "strings"
)

func main() {
    //Enter your code here. Read input from STDIN. Print output to STDOUT



    for commands.Scanner.Scan() {

        //scan a new line and send it to comand variable to check command exist or not
        input := strings.Split(strings.Trim(commands.Scanner.Text(), " "), " ")
        command := input[0]

        if command == "" {
            fmt.Printf("$ %s:", commands.Pwd)
            continue
        }

        if !commands.Commands[command] {
            commands.ThrowError("CANNOT RECOGNIZE INPUT.")

        } else {

            commands.Execute(command, input[1:], nil)

        }
        fmt.Printf("$ %s:", commands.Pwd)
    }
}

我也在主包中使用init.go文件如下

package main

import (
    "flag"
    "player/source"
)

func init() {
    sourceFlag := flag.String("filename", "", "if input is through source file")
    flag.Parse()
    if *sourceFlag != "" {
        source.Input(*sourceFlag)
    }
}

我的最终包播放器/源如下:-

package source

    import (
        "bufio"
        "log"
        "os"
        "player/command"
    )

    func Input(source string) {
        if source != "" {
            readFile, err := os.OpenFile(source, os.O_RDONLY, os.ModeExclusive)
            if err != nil {
                log.Fatal(err)
            }
            commands.Scanner = bufio.NewScanner(readFile)
            writeFile, err := os.Create(source + "_output.txt")
            if err != nil {
                log.Fatal(err)
            }
            commands.Writer = bufio.NewWriter(writeFile)
        } else {
            commands.Scanner = bufio.NewScanner(os.Stdin)
            commands.Writer = bufio.NewWriter(os.Stdout)
            // fmt.Println(commands.Scanner)
        }
    }

执行此代码会导致

panic: runtime error: invalid memory address or nil pointer dereference
[signal 0xb code=0x1 addr=0x58 pc=0x4a253a]

goroutine 1 [running]:
bufio.(*Scanner).Scan(0x0, 0x5)
    /usr/local/go/src/bufio/scan.go:120 +0x2a
main.main()
    /home/xyz/dev/go/src/players/main.go:13 +0x124

即使在初始化我的扫描仪后,我也不知道为什么我无法从中读取数据

【问题讨论】:

  • 当您收到错误消息时,您是否尝试从stdin 读取数据?还是在向 main 提供输入文件时也会发生这种情况?
  • 请提供恐慌的全部输出。

标签: go scanning


【解决方案1】:

command.Scanner 未初始化的一个原因可能是您没有将 filename 参数传递给主脚本。在这种情况下,永远不会调用 source.Input(*sourceFlag),根据 if 条件(如果缺少 filename 选项,if *sourceFlag != "" 为假)。

另外,由于您稍后在source 中检查空文件名,因此maininit 中的这个条件是多余的。试试:

func init() {
    sourceFlag := flag.String("filename", "", "if input is through source file")
    flag.Parse()
    source.Input(*sourceFlag)
}

【讨论】:

    猜你喜欢
    • 2015-02-24
    • 2022-01-05
    • 1970-01-01
    • 2019-09-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-23
    • 2012-07-21
    相关资源
    最近更新 更多