duancan1900 2019-03-09 16:33
浏览 61

在全局配置结构中使用不同的数据库结构

I have a global config for most settings (e.g. Logfiles) which I use in all Projects, for example:

project config

type Config struct {
    Logfile string
    Loglevel string
    Database *database.Database
}

The config itself has its own project, the database has its own projects and the implementation is done in its own project. (So I have config project, database project, and app project).

I want every Project to implement the database itself since all of them have different functions attached to it. Since I don't want multiple fields for every database, I have a minimum interface which is satisfied by all Database Implementations

project database

// This interface is referenced by the Config struct using *database.Database
type Database interface {
    InitDatabase() error
}

type AppDatabase interface {
    InitDatabase() error // To satisfy the Database interface
    AdditionalFunction1() 
    AdditionalFunction2()
}

type OtherAppDatabase interface {
    InitDatabase() error
    OtherFunc1() 
}

When I want to implement the database, I want to assign the new database struct to the (project-) global configuration (e.g config.Database).

However, this does not work as I cannot assign the new struct (which implements the database interface) to the conf.Database interface, e.g.

project app 

type OtherAppDatabase struct {
    *sql.DB
}

func (db *OtherAppDatabase) InitDatabase() error {
    conf := config.GetConfig() // this just returns the global config file

    conf.Database = d // This does not work [1]
}

func (db *OtherAppDatabase) OtherFunc1() {}

[1]: Cannot use 'db' (type *OtherAppDatabase) as type *database.Database in assignment Inspection info: Reports incompatible types in binary and unary expressions.

Is there a way to keep one database field in the global config and assign the specific database to it as needed?

Thanks and best regards,

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥20 测距传感器数据手册i2c
    • ¥15 RPA正常跑,cmd输入cookies跑不出来
    • ¥15 求帮我调试一下freefem代码
    • ¥15 matlab代码解决,怎么运行
    • ¥15 R语言Rstudio突然无法启动
    • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
    • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
    • ¥15 用windows做服务的同志有吗
    • ¥60 求一个简单的网页(标签-安全|关键词-上传)
    • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法