go之多个数据库驱动程序场景 : passing interface as type

qlqwjy 阅读:183 2025-06-02 22:19:02 评论:0

场景:我有一个数据库类型实现了一些 CRUD 操作。

我想:

  • 抽象出数据库层以支持多个数据库
  • 将缓存层“放在它前面”作为读取缓存

  • 所以我的想法是:
  • 为 postgres 特定代码和缓存创建数据库接口(interface)
  • 将 postgres 类型传递给缓存构造函数,以便它可以从数据库
  • 中使用它

    请参阅下面的内容,了解我在分配时导致 cacheNew() 错误:

    cannot use dbdriver (variable of type interface{}) as database value in struct literal: missing method GetUser



    解决这个问题的最佳方法是什么?
    package main 
     
    import "fmt" 
     
    type database interface { 
        GetUser(string) 
    } 
     
    type postgres struct { 
        hostname string 
    } 
     
    func (p *postgres) GetUser(u string) { 
        fmt.Printf("Postgres: GetUser %s\n", u) 
    } 
     
    type cache struct { 
        db database 
    } 
     
    func cacheNew(dbdriver interface{}) cache { 
        return cache{ 
            db: dbdriver, 
        } 
    } 
     
    func (c *cache) GetUser(u string) { 
        fmt.Printf("Cache: GetUser %s\n", u) 
     
        c.db.GetUser(u) 
    } 
     
    func main() { 
        // var db database 
     
        db := postgres{ 
            hostname: "x", 
        } 
        db.GetUser("joe") 
     
        dbViaCache := cacheNew(db) 
        dbViaCache.GetUser("joe") 
    } 
    

    请您参考如下方法:

    为了解决您的问题,添加 newPostgres 构造函数。下面我对您的初始代码进行了更正。

    package main 
     
    import "fmt" 
     
    type database interface { 
        GetUser(string) 
    } 
     
    type postgres struct { 
        hostname string 
    } 
     
    func newPostgres(hostname string) *postgres { 
        return &postgres{ 
            hostname: hostname, 
        } 
    } 
     
    func (p *postgres) GetUser(u string) { 
        fmt.Printf("Postgres: GetUser %s\n", u) 
    } 
     
    type cache struct { 
        db database 
    } 
     
    func cacheNew(db database) cache { 
        return cache{ 
            db: db, 
        } 
    } 
     
    func (c *cache) GetUser(u string) { 
        fmt.Printf("Cache: GetUser %s\n", u) 
     
        c.db.GetUser(u) 
    } 
     
    func main() { 
        db := newPostgres("x") 
     
        db.GetUser("joe") 
     
        dbViaCache := cacheNew(db) 
        dbViaCache.GetUser("joe") 
    } 
    


    标签:数据库
    声明

    1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。

    关注我们

    一个IT知识分享的公众号