不能将nil用作类型模型。return参数中的文章

I have this function which is supposed to query database and return an article if found, and nil if the article is not found:

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
}

Where Article is a struct defined in model package.

But I get this error:

cannot use nil as type model.Article in return argument

How can I fix this?

nil is only a valid value for pointer, slices, and maps. You cannot have a nil struct value, for example.

Typically in a function like this your error return would be e.g.

return model.Article{}, err

to return an empty struct.

If you want to return the nil in case of error, update your function to this

    func GetArticleBySlug(slug string) (*model.Article, error) {
    var err error
    article := new(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
}