具有接收指定接口(interface)参数的函数的 Golang 接口(interface)

标签 go interface

我正在尝试在 Go 中使用接口(interface)来获得两个优势:

  • 保护自己不要混淆变量命令
  • 使包装彼此独立,因此有一天我可以轻松更换其中一个。

  • 在我的特殊情况下,我可以找到 workaroung,但我不明白为什么我尝试的方式行不通,它看起来简单且合乎逻辑。
    这就是我所做的。
    在一个包(命名处理程序)中,我有一个描述我需要的函数的接口(interface),只是接收 Account 的东西。 .
    package handlers
    
    type Accounter interface {
        AddAccount(a Account)
    }
    
    type Account interface {
        AccountID() int64
        UserID() int64
        OtherID() int64
    
    }
    
    在我的程序的其他包(名为 accounter)中,我具有与接口(interface)匹配的功能,以及 Account 的定义interface 以避免从第一个包中导入此接口(interface)。
    package accounter
    
    type Account interface {
        AccountID() int64
        UserID() int64
        OtherID() int64
    }
    
    func (x *accounter) AddAccount(a Account) {
    ...
    }
    
    但是 go vet告诉我我不能做这样的事情:
    configure_stats_loader.go:109:64: cannot use x (type *accounter.Accounter) as type handlers.Accounter in argument to handlers.AddAccHandler:
        *accounter.Accounter does not implement handlers.Accounter (wrong type for AddAccount method)
            have AddAccount(accounter.Account)
            want AddAccount(handlers.Account)
    
    在这种情况下,我必须解决:
  • 进口 Account来自其中一个包的接口(interface)。
  • 在标准 go 类型中定义函数接收值,如 (UserID, AccoutID, OtherID int64) .

  • 在第一种情况下,我在包中失去了独立性,并且在将来我将无法替换 Accounter接口(interface)而不重写一些代码(不是很多代码,但仍然),在第二种情况下,如果我在Account中有很多类似的方法和很多参数,我可能会不小心混淆了变量的顺序。例如误用 AccountIDUserID .
    现在的问题是:有什么方法可以拥有所有优势吗?防止混淆变量顺序并避免从一个包导入到另一个包。

    最佳答案

    与@Marc 评论相呼应,“第三方”包非常适合定义常见类型。这是常见的做法,尤其是在处理 gRPC generated code 时。 .
    同样根据 Effective Go保持接口(interface)简短:

    Interfaces with only one or two methods are common in Go code


    因此,请避免费力的 getter/setter 定义 - 并专注于更大的操作。所以我建议在你的“类型”包中:
    package mydefs
    
    // concrete type: used for Creation and lookup
    type Account struct {
        ID      int64
        UserID  int64
        OtherID int64
    }
    
    // abstract interface: keep method list short
    type Accounter interface {
        Add(a Account) error             //
        Get(a Account) (Account, error)  // use concrete type as a lookup request type
    }
    

    关于具有接收指定接口(interface)参数的函数的 Golang 接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63229779/

    相关文章:

    去错误: non-constant array bound

    testing - 如果直接访问其字段,如何模拟结构

    android - 单击核心游戏 LibGDX 上的按钮时调用 Activity

    java - 多态性最佳实践

    Java 接口(interface)层次结构及其具有有界类型泛型的方法

    go - 为什么 Go 中的错误可以为零?

    angular - 在 golang 中对 AES 解密的 panic 返回

    Go build, with module, 在 Alpine 镜像下失败,但在 Windows 下没问题

    java - golang 中 key 长度为 15360 的 RSA key 对生成速度太慢。需要做些什么来解决这个问题?

    go - 无法通过串口解析GPS信息