doulou1989 2017-06-17 03:50
浏览 9
已采纳

在函数上需要类型断言

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条回答 默认 最新

  • dream_wu2015 2017-06-17 04:13
    关注

    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))
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥25 关于##爬虫##的问题,如何解决?:
  • ¥15 ZABBIX6.0L连接数据库报错,如何解决?(操作系统-centos)
  • ¥15 找一位技术过硬的游戏pj程序员
  • ¥15 matlab生成电测深三层曲线模型代码
  • ¥50 随机森林与房贷信用风险模型
  • ¥50 buildozer打包kivy app失败
  • ¥30 在vs2022里运行python代码
  • ¥15 不同尺寸货物如何寻找合适的包装箱型谱
  • ¥15 求解 yolo算法问题
  • ¥15 虚拟机打包apk出现错误