什么原因导致"panic: runtime error: invalid memory address or nil pointer dereference"?



我的项目有问题。

收到错误:

panic:运行时错误:无效的内存地址或 nil 指针取消引用 [信号 SIGSEGV:分段违规代码=0x1 地址=0x0 pc=0x44c16f]

我做错了什么?

套餐 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 ""
}

套餐 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")
}

主去

package main
import (
    "github.com/lathrel/test/b"
)
func main() {
    b.InitB()
}

查看包b

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

您可以看到您使用新Controller启动了新App{},但您没有填写Controller内的界面。接口是期望类型中的某个方法的东西。

这是一个可以解决这个问题的快速片段:

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")
}

游乐场链接: https://play.golang.org/p/ZfEqdr8zNG-

相关内容

最新更新