// 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)
}
在上面的代码中,GetById 的参数定义是c echo.Context, id int
. 只需要两个参数。但是编译器会提醒我,例如“调用方法表达式 models.User.GetById 的参数不足”
有什么问题?