2
golang 一个函数返回不同的结构体有比较优雅的实现吗
source link: https://www.v2ex.com/t/812453
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
我现在要定义一个函数,根据入参返回不同的配置,一个比较简单的复现
type MysqlConfig struct{}
type MongoConfig struct{}
func newCfg(source string) Config{
}
我现在是把 Config 定义成 type Config map[string]interface{}; 刚开始用 go ,请问有没有比较优雅的实现方式
7 条回复 • 2021-11-02 16:01:21 +08:00
hellodudu86 1 小时 41 分钟前
package main
import "fmt"
type MysqlConfig struct{}
type MongoConfig struct{}
func newCfg(source string) interface{} {
if source == "mysql" {
return &MysqlConfig{}
} else {
return &MongoConfig{}
}
}
func main() {
mysqlCfg := newCfg("mysql").(*MysqlConfig)
mongoCfg := newCfg("mongo").(*MongoConfig)
fmt.Printf("%T\n%T\n", mysqlCfg, mongoCfg)
}
import "fmt"
type MysqlConfig struct{}
type MongoConfig struct{}
func newCfg(source string) interface{} {
if source == "mysql" {
return &MysqlConfig{}
} else {
return &MongoConfig{}
}
}
func main() {
mysqlCfg := newCfg("mysql").(*MysqlConfig)
mongoCfg := newCfg("mongo").(*MongoConfig)
fmt.Printf("%T\n%T\n", mysqlCfg, mongoCfg)
}
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK