gpt4 book ai didi

dictionary - 接受多种接口(interface)类型的数据类型

转载 作者:行者123 更新时间:2023-12-01 21:10:39 24 4
gpt4 key购买 nike

我会尽力在这里解释我的情况。

所以,我正在为我的应用程序创建一个 DAL。它同时访问redis和mysql。

redis接口(interface)如下:

文件 NoSqlDBClient.go:

type NosqlDb interface {
HGet() string
}

type NosqlClient struct {
key string
}

func GetNosqlClient() *NosqlClient{
return &NosqlClient{}
}

func (ns *NosqlClient) HGet()string {
//actual implemenation would be different
return ns.key
}

文件 SqldbClient.go:
type SqlDB interface {
ExecQuery()
}

type SqlClient struct {
query string
}

func GetsqlClient() *SqlClient{
return &SqlClient{}
}

func (s *SqlClient) ExecQuery()string {
//actual implemenation would be different
return s.query
}

现在我需要实现一个 DBClient Factory,它维护一个 dbtype 和客户端的映射。
它是这样的

文件 DBClientFactory.go
type DBClientfactory struct {
clientmap[string] //what data type to use???
}

func GetNoSqlDBClient() NosqlDb{
client:=NoSqlDBClient.GetNosqlClient()
clientmap['nosql'] = client
return client
}

func GetSqlDBClient() SqlDB{
client:=SqlDBClient.GetsqlClient()
clientmap['sql'] = client
return client
}

问题是如何在一张 map 中容纳不同类型的客户?
我想定义另一个接口(interface) DBFactory其中嵌入了其他两个接口(interface)。但这显然行不通,因为所有方法都不是由单个接口(interface)实现的。

我该如何解决这个问题?

最佳答案

您可以使用 interface{}对于映射值类型,但是您会失去类型安全性,并且必须使用类型断言或类型切换。

相反,您应该使用 2 种不同的 map 类型,一种用于您要存储的每个接口(interface):

type DBClientfactory struct {
nosqldbs map[string]NosqlDb
sqldbs map[string]SqlDB
}

并且每个函数或方法都将使用适当的映射 GetNoSqlDBClient()将使用 DBClientfactory.nosqldbs , 和 GetSqlDBClient()将使用 DBClientfactory.sqldbs .

如果每个客户端只有一个实例,则根本不要使用 map ,只需使用简单的字段:
type DBClientfactory struct {
nosqldb NosqlDb
sqldb SqlDB
}

关于dictionary - 接受多种接口(interface)类型的数据类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61453807/

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