-1
// user.go
package models

type User struct {
    Id        int       `db:"id" json:"id"`
    CreatedAt time.Time `db:"created_at" json:"created_at"`
    UpdatedAt time.Time `db:"updated_at" json:"updated_at"`
}

func (User) GetById(c echo.Context, id int) (*User, error) {
    db := c.Get("DB").(*sqlx.DB)
    user := User{}
    err := db.Get(&user, fmt.Sprintf("SELECT id, created_at, updated_at FROM users WHERE id=%d", id))
    if err != nil {
        fmt.Println(err)
    }
    return &user, err
}
// main.go
package main

// Success
func fetch_success(c echo.Context) error {
    user := models.User{}
    user2, err := models.User.GetById(user, c, 5)
}


// Fail: : not enough arguments in call to method expression models.User.GetById
//         have (echo.Context, number)
//         want (models.User, echo.Context, int)
func fetch_failure(c echo.Context) error {
    user, err := models.User.GetById(c, 5)
}

In the above code, argument definition for GetById is c echo.Context, id int. Just two argument is needed. But compiler alert me such as "not enough arguments in call to method expression models.User.GetById"

What's the problem?

jeyraof
  • 863
  • 9
  • 28

1 Answers1

3

You are calling a method GetById but not on an object. When Go calls a method, it supplies the object as a first parameter implicitly. It is similar to passing self reference in Python but syntactically it goes between func keyword and function name.

Rewrite it to be a function:

func GetUserById(c echo.Context, id int) (*User, error) {
    db := c.Get("DB").(*sqlx.DB)
    user := User{}
    err := db.Get(&user, fmt.Sprintf("SELECT id, created_at, updated_at FROM users WHERE id=%d", id))
    if err != nil {
        fmt.Println(err)
    }
    return &user, err
}

and then call

user, err := models.GetUserById(c, 5)
Grzegorz Żur
  • 47,257
  • 14
  • 109
  • 105
  • Wow.. I couldnt avoid from oop. Thank you very much. I think I had wrong approach to implement like oop's class method. – jeyraof Mar 27 '20 at 12:22