-1

我有以下函数应该从我的想法表中检索一行:

func (s *IdeaService) GetIdea(id int64) (*ideaservice.Idea, error) {
    stmt, err := s.DB.Prepare("SELECT id, name, description, created_on, last_updated FROM ideas WHERE id = $1")
    if err != nil {
        return nil, err
    }
    defer stmt.Close()
    var idea *ideaservice.Idea
    err = stmt.QueryRow(id).Scan(&idea.ID, &idea.Name, &idea.Description, &idea.CreatedOn, &idea.LastUpdated)
    return idea, err
}

当我在测试中运行它时,会出现以下错误:

--- FAIL: TestGetIdea (0.00s)
panic: runtime error: invalid memory address or nil pointer dereference [recovered]
    panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x1 addr=0x0 pc=0x65be98]

我似乎无法弄清楚问题所在。我相信我已经将 idea var 正确地实例化为指针,然后我在 Scan 方法中为其赋值。有没有人有什么建议?

4

1 回答 1

0
func (s *IdeaService) GetIdea(id int64) (*ideaservice.Idea, error) {
    stmt, err := s.DB.Prepare("SELECT id, name, description, created_on, last_updated FROM ideas WHERE id = $1")
    if err != nil {
        return nil, err
    }
    defer stmt.Close()
    var idea *ideaservice.Idea
    err = stmt.QueryRow(id).Scan(&idea.ID, &idea.Name, &idea.Description, &idea.CreatedOn, &idea.LastUpdated)
    return idea, err
}

能不能换$1一个?看看好不好用?在stmt.QueryRow你通过id. 像这样:

stmt, err := s.DB.Prepare("SELECT id, name, description, created_on, last_updated FROM ideas WHERE id = ?")

如果它不起作用,则添加此块:

switch {
    case err == sql.ErrNoRows:
        log.Fatalf("no user with id %d", id)
    case err != nil:
        log.Fatal(err)
    default:
        log.Println("ok!")
    }

更新:没有看到关于这个问题的评论。是的,他也是正确的。也要修复它们。

并检查err被困在哪里(在这种情况下)。

于 2020-04-17T18:12:46.970 回答