我的项目有问题。
获取错误:
紧急:运行时错误:无效的内存地址或nil指针取消引用 [signal SIGSEGV:细分违规代码= 0x1 addr = 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")
}
main.go
package main
import (
"github.com/lathrel/test/b"
)
func main() {
b.InitB()
}
答案 0 :(得分:1)
查看软件包b
:
// InitB inits B :)
func InitB() {
app := App{}
app.fine.Fine("hi")
}
您可能会看到您用新的App{}
来初始化新的Controller
,但没有在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")
}