2

golang 一个函数返回不同的结构体有比较优雅的实现吗

 2 years ago
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.
neoserver,ios ssh client

V2EX  ›  Go 编程语言

golang 一个函数返回不同的结构体有比较优雅的实现吗

  evan0724 · 2 小时 10 分钟前 · 332 次点击

我现在要定义一个函数,根据入参返回不同的配置,一个比较简单的复现

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

sujin190

sujin190   2 小时 8 分钟前

声明一个 interface 呗,MysqlConfig 和 MongoConfig 都实现这个接口不就好了

evan0724

evan0724   2 小时 2 分钟前

@sujin190 MysqlConfig 和 MongoConfig 里面的字段是不同的

sujin190

sujin190   2 小时 1 分钟前

@evan0724 #2 interface 本来就没要求你两个结构体字段一样啊,要的是都支持相同的操作

evan0724

evan0724   1 小时 59 分钟前

@sujin190 嗯,我看到过这种实现,就是需要在接口里面一如一个方法吧

hellodudu86

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

evan0724

evan0724   1 小时 38 分钟前

@sujin190 确实这种实现比较好,我一开始想错了,谢谢回复

LoNeFong

LoNeFong   27 分钟前

工厂模式?

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK