Cannot convert nil (untyped nil value) to struct

go
12,980

Using a pointer return type is perfectly fine.

If you would rather return a non-pointer struct, then simply return a zero value of the struct:

return pg.User{}, err

or change your function signature to include return named variables (note: the use of = not := as the variables are already considered declared):

func (u *user) Create(ctx context.Context, db *sql.DB) (u pg.User, err error) {
    q := pg.New(db)
    u, err = q.CreateUser(ctx, "Someone")
    
    return // will implicitly return u & err for you
}

and since the if err logic has been removed, the above can be reduced to a one-liner:

func (u *user) Create(ctx context.Context, db *sql.DB) (pg.User, error) {
    return pg.New(db).CreateUser(ctx, "Someone")
}
Share:
12,980

Related videos on Youtube

Rario
Author by

Rario

Updated on June 04, 2022

Comments

  • Rario
    Rario almost 2 years

    A Go noob's learning to use sqlc here. I'm trying to create a method that creates a user.

    How do I return nil for a struct?

    type user struct{}
    
    func (u *user) Create(ctx context.Context, db *sql.DB) (pg.User, error) {
        q := pg.New(db)
        user, err := q.CreateUser(ctx, "Someone")
        if err != nil {
            return nil, err
            //      ^
            // [compiler] [E] cannot convert nil (untyped nil value) to pg.User
        }
        return user, nil
    }
    

    This is the pg.User struct:

    type User struct {
        ID int64 `json:"id"`
        // can not be empty
        Name      string    `json:"name"`
        CreatedAt time.Time `json:"created_at"`
        UpdatedAt time.Time `json:"updated_at"`
    }
    

    Currently, I'm returning pointer instead, which gives no error:

    func (u *user) Create(ctx context.Context, db *sql.DB) (*pg.User, error) {
        q := pg.New(db)
        var usr *pg.User
        user, err := q.CreateUser(ctx, "Someone")
        if err != nil {
            return nil, err
        }
    
        fmt.Println(">> user:", user)
        // >> user: {1 Someone 2020-09-14 18:36:05.94079 +0000 UTC 2020-09-14 18:36:05.94079 +0000 UTC}
    
        usr = &user
        fmt.Println(">> usr:", usr)
        // >> usr: &{1 Someone 2020-09-14 18:36:05.94079 +0000 UTC 2020-09-14 18:36:05.94079 +0000 UTC}
    
        return usr, nil
    }
    

    One more question though, which one is better, returning pointer or not?