dtjxhf595733 2018-03-03 13:36
浏览 30
已采纳

Golang参数转换

Can somebody explain how can this happened?

I put interface as parameter in a function. While invoking this function I pass struct into it, but it didn't give me error. Here's the code

package main

import (
    "fmt"
    "github.com/myusername/gomodel/domain"
    "github.com/myusername/gomodel/model"
)

func main() {
    db := model.InitDB()

    newFunc(db)
}


func newFunc(db domain.IUser) {

    r, err := db.CreateUserTable()
    if err != nil {
        fmt.Println("error", err)
    }
    fmt.Println(r)
}

I've implemented the interface somewhere else in the code, because the program just work as the implemented interface expected to be. IUser is an interface whose member is:

type IUser interface {
    CreateUserTable() (sql.Result, error)
}

InitDB is a function to open the database and return struct of database:

type DB struct {
    *sql.DB
}

//InitDB initializes the database
func InitDB() *DB {
    db, err := sql.Open(dbDriver, dbName)
    if err != nil {
        log.Fatal("failed to initialize database: ",err)
    }
    err2 := db.Ping()
    if err2 != nil {
        log.Fatal(err2)
    }

    return &DB{db}
}

My question is: how can a function with a parameter type interface be passed a different type of parameter? And how is this working under the hood?

  • 写回答

1条回答 默认 最新

  • doutui7955 2018-03-03 13:44
    关注

    As per Golang Spec

    An interface type specifies a method set called its interface. A variable of interface type can store a value of any type with a method set that is any superset of the interface. Such a type is said to implement the interface.

    This is because interface can be implemented as a wrapper to every type. Interface actually points to two things mainly one is the underlying type which is a struct here and other one is the value of that type which is a pointer to DB

    You see newFunc is actually taking interface{} as an argument, So you can pass anything to it of type T which can be of primitive types too.

    func main() {
        db := model.InitDB()
    
        newFunc(db)
    }
    

    So In case you want to get the underlying value you need to type assert. Interface works like a wrapper to the struct here and save its type and value which can be get using type assertion.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥120 计算机网络的新校区组网设计
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单