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?