drtohng5613 2019-04-07 01:52
浏览 3

是什么导致“紧急:运行时错误:无效的内存地址或nil指针取消引用”? [关闭]

I'm having a problem with my project.

getting the error:

panic: runtime error: invalid memory address or nil pointer dereference [signal SIGSEGV: segmentation violation code=0x1 addr=0x0 pc=0x44c16f]

What am I doing wrong?

package A

package a

import (
    "fmt"

    "github.com/lathrel/test/b"

)

type (
    // App ...
    App b.App
)

// Fine is a fine :) but was fine :/
func (app *App) Fine(str string) string {
    fmt.Println(str)
    return ""
}

package B

package b

// App is a test
type App struct {
    fine Controller
}

// Controller is a test
type Controller interface {
    Fine(str string) string
}

// InitB inits B :)
func InitB() {
    app := App{}

    app.fine.Fine("hi")
}

main.go

package main

import (
    "github.com/lathrel/test/b"
)

func main() {
    b.InitB()
}
  • 写回答

1条回答 默认 最新

  • drxzpo70788179614 2019-04-07 02:08
    关注

    Looking at package b:

    // InitB inits B :)
    func InitB() {
        app := App{}
    
        app.fine.Fine("hi")
    }
    

    You could see that you initalized a new App{} with a new Controller but you didn't fill in the Interface inside the Controller. An interface is something that expects a certain method from a type.

    Here's a quick snippet that would solve it:

    type NotFine struct{}
    
    // Fine is a method of NotFine (type struct)
    func (NotFine) Fine(str string) string {
        fmt.Println(str)
        return ""
    }
    
    // InitB, ideally, would take in the interface itself,
    // meaning, the function becomes InitB(c Controller).
    // You then initiate `app := App{fine: c}`.
    // This is implemented in https://play.golang.org/p/ZfEqdr8zNG-
    func InitB() {
        notfine := NotFine{}
        app := App{
            fine: notfine,
        }
    
        app.fine.Fine("hi")
    }
    

    Playground link: https://play.golang.org/p/ZfEqdr8zNG-

    评论

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?