需要在函数上进行类型断言。

huangapple go评论71阅读模式
英文:

Need type assertion on functions

问题

我正在尝试学习类型断言和类型转换,对我来说有点复杂。

我有这个例子:(我正在使用gin框架)

type Env struct {
    db *sql.DB
}

func main() {
    r := gin.Default()

    // 初始化会话管理(基于cookie)
    store := sessions.NewCookieStore([]byte("secret"))
    r.Use(sessions.Sessions("mysession", store))

    db, _ := sql.Open("sqlite3", "./libreread.db")
    defer db.Close()

    env := &Env{db: db}
    r.GET("/", env.GetHomePage)
}

func (e *Env) _GetUserId(email string) int64 {
    rows, err := e.db.Query("SELECT `id` FROM `user` WHERE `email` = ?", email)
    CheckError(err)

    var userId int64
    if rows.Next() {
        err := rows.Scan(&userId)
        CheckError(err)
    }
    rows.Close()

    return userId
}

func (e *Env) GetHomePage(c *gin.Context) {
    session := sessions.Default(c)
    email := session.Get("email")

    if email != nil {
        name := c.Param("bookname")
        userId := e._GetUserId(email) // 我在这里卡住了。
    }
}

所以,在上面的代码中...我正在设置db Env类型并将其传递给路由函数。从那里,我需要调用另一个函数。如何做到这一点?

当我调用e._GetUserId(email)时,它显示:

无法将email(类型为interface {})转换为Env类型:需要类型断言

如何解决这个问题?我需要在Env类型中使用interface{}而不是struct吗?

英文:

I'm trying to learn type assertion and conversion. It's kinda complicated for me.

I have this example: (I'm using gin framework)

type Env struct {
	db *sql.DB
}

func main() {
    r := gin.Default()

    // Initiate session management (cookie-based)
    store := sessions.NewCookieStore([]byte("secret"))
    r.Use(sessions.Sessions("mysession", store))

    db, _ := sql.Open("sqlite3", "./libreread.db")
    defer db.Close()

    env := &Env{db: db}
    r.GET("/", env.GetHomePage)
}

func (e *Env) _GetUserId(email string) int64 {
    rows, err := e.db.Query("SELECT `id` FROM `user` WHERE `email` = ?", email)
    CheckError(err)

    var userId int64
    if rows.Next() {
	    err := rows.Scan(&userId)
	    CheckError(err)
    }
    rows.Close()

    return userId
}

func (e *Env) GetHomePage(c *gin.Context) {
    
    session := sessions.Default(c)
    email := session.Get("email")

    if email != nil {
	    name := c.Param("bookname")
	    userId := e._GetUserId(email) // I'm stuck here.
}

So, in the above code.. I'm setting db Env type and passing it to router functions. From there, I need to call another function. How to do that?

When I call e._GetUserId(email), it says

cannot convert email (type interface {}) to type Env: need type assertion

How to solve this problem?. Do I need to use inferface{} instead of struct for Env type?

答案1

得分: 7

根据我评论中的对话起草答案。

方法 session.Get("email") 返回 interface{} 类型。

而方法 e._GetUserId() 接受字符串参数,所以你需要进行类型断言,如下所示 -

e._GetUserId(email.(string))
英文:

Drafting answer based on conversation from my comments.

Method session.Get("email") returns interface{} type.

And method e._GetUserId() accepts string parameter, so you need to do type assertion as string like -

e._GetUserId(email.(string))

huangapple
  • 本文由 发表于 2017年6月17日 11:50:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/44600570.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定