gpt4 book ai didi

Golang 参数转换

转载 作者:IT王子 更新时间:2023-10-29 02:02:13 26 4
gpt4 key购买 nike

有人可以解释这是怎么发生的吗?

我把 interface 作为函数的参数。在调用此函数时,我将 struct 传递给它,但它没有给我错误。这是代码

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)
}

我已经在代码中的其他地方实现了接口(interface),因为程序只是按照预期的实现接口(interface)工作。IUser 是一个接口(interface),其成员是:

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

InitDB是一个打开数据库并返回数据库结构的函数:

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}
}

我的问题是:具有参数类型接口(interface)的函数如何传递不同类型的参数?这在幕后是如何运作的?

最佳答案

根据 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.

这是因为接口(interface)可以作为每个类型的包装器来实现。接口(interface)实际上指向两件事,一个是底层类型,这里是一个结构体,另一个是该类型的值,它是一个指向 DB 的指针

您看到 newFunc 实际上将 interface{} 作为参数,因此您可以将任何类型的 T 传递给它,它可以是也是原始类型。

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

newFunc(db)
}

所以如果你想获得你需要输入断言的基础值。接口(interface)就像这里结构的包装器一样工作,并保存它的类型和值,可以使用类型断言获取。

关于Golang 参数转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49084723/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com