go - 不能使用 nil 作为类型模型。返回参数中的文章

标签 go

<分区>

我有这个函数,它应该查询数据库并返回 article 如果找到,如果找不到文章则返回 nil:

func GetArticleBySlug(slug string) (model.Article, error) {
    var err error
    var article model.Article
    err = database.SQL.Get(&article, "SELECT * FROM article WHERE slug=? LIMIT 1", slug)
    if err != nil {
        log.Println(err)
        return nil, err //<- Problem here
    }
    return article, nil
}

其中 Article 是在 model 包中定义的结构。

但是我得到这个错误:

cannot use nil as type model.Article in return argument

我该如何解决这个问题?

最佳答案

nil 只是指针、 slice 和映射的有效值。例如,您不能有一个 nil 结构值。

通常在这样的函数中,您的错误返回将是例如

return model.Article{}, err

返回一个空结构。

关于go - 不能使用 nil 作为类型模型。返回参数中的文章,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57465968/

相关文章:

http - Golang根据struct字段设置http响应码

go - 函数改变字节 slice 参数

go - 选择完成后,这个 FOR 循环如何中断

html 电子邮件正文中的 gomail.v2 quoted-printable 编码问题

git - 从私有(private)存储库获取依赖项的正确方法

csv - Golang读取csv占用的内存空间比磁盘多2倍

go - 为什么Go子程序不被执行

go - 如何查看Psql是否成功更新了Go中的记录

dictionary - 是否可以在包含 map 名称的同时编码一个 go 结构?

validation - Revel 中的表单输入验证