Go 接口返回运行时错误:无效内存地址或零指针取消引用

Go 接口返回运行时错误:无效内存地址或零指针取消引用,go,Go,我已经用Go创建了一些代码,并尝试实现一个接口 有一个接口 type CityInterface interface { GetAll() (models.CityResponses, error) } 然后在带有相同接口文件包的分离文件上引用此函数 //GetAll is a function to get all city func GetAll() (models.CityResponses, error) { .... return cities, err }

我已经用Go创建了一些代码,并尝试实现一个接口

有一个接口

type CityInterface interface {
    GetAll() (models.CityResponses, error)
}
然后在带有相同接口文件包的分离文件上引用此函数

//GetAll is a function to get all city
func GetAll() (models.CityResponses, error) {
    ....

    return cities, err
}
然后,我使用该接口为文件和包服务提供服务

func GetAllCity() (models.CityResponses, error) {
    var cityInterface repositories.CityInterface
    cities, err := cityInterface.GetAll()

    return cities, err
}
为什么此脚本返回紧急运行时错误:无效内存地址或零指针取消引用

这是指这条线

cities, err := cityInterface.GetAll()

请帮我找出这个问题。谢谢。

至少有两个问题:

  • 接口方法的实现应该是一个成员函数
  • 变量
    cityInterface
    未初始化为任何有用的值
  • 此行声明类型为
    repositories.CityInterface
    的变量,并指定零值。所有接口类型的零值均为零

    在nil接口上调用方法会引起您观察到的恐慌(如果接口值中没有存储具体类型,运行时还能做什么?)

    看起来您正在尝试使用包级函数
    GetAll
    实现接口。这不是它的工作原理。接口是由类型而不是包实现的

    要实现
    CityInterface
    ,请使用
    GetAll
    方法定义类型,而不仅仅是名为
    GetAll
    的函数,并使用此类型的值初始化接口

    type T struct {}
    
    func (T) GetAll() (models.CityResponses, error) {
        // Body of original GetAll function goes here.
    }
    
    func GetAllCity() (models.CityResponses, error) {
        var cityInterface repositories.CityInterface = T{} // initialize interface value
        cities, err := cityInterface.GetAll()
    
        return cities, err
    }
    

    或者,去掉该接口并
    GetAllCity
    ;这只是直接调用原始的
    GetAll
    函数的一种复杂方式。

    您是在nil上调用GetAll。您是否希望
    cityInterface
    不是零?如果是,为什么?它只是“走”,而不是“走郎”或“咕噜”。就像它不是“PythonLang”或“JavaLang”一样,只在谷歌搜索上搜索“Go”是模棱两可的。谢谢,我现在明白了。
    type T struct {}
    
    func (T) GetAll() (models.CityResponses, error) {
        // Body of original GetAll function goes here.
    }
    
    func GetAllCity() (models.CityResponses, error) {
        var cityInterface repositories.CityInterface = T{} // initialize interface value
        cities, err := cityInterface.GetAll()
    
        return cities, err
    }