能否说服Golang编译器将`type Foo int`视为`int`?

huangapple go评论80阅读模式
英文:

Is it possible to convince the Golang compiler to accept `type Foo int` as an `int`?

问题

我正在使用Go语言的pebbe/zmq4 ZeroMQ绑定库,并且我正在尝试为我的代码开发更高级别的接口,以支持在测试中进行模拟。

以我的问题为例,zmq4.Socket结构体的RecvMessage函数需要一个zmq4.Flag作为参数。zmq4.Flag只是一个int,在Go绑定中定义为type Flag int

我正在尝试开发与ZeroMQ绑定库无关的接口,所以我定义了一个接口:

type Socket interface {
    RecvMessage(int) ([]string, error)
}

当我尝试在这个接口中使用ZeroMQ socket时,我收到一个错误,错误信息为... have RecvMessage(zmq4.Flag) ([]string, error) want RecvMessage(int) ([]string, error)

有没有办法解决这个问题,或者我只需要接受在我的接口中依赖ZeroMQ绑定库?

英文:

I'm using the pebbe/zmq4 ZeroMQ bindings for Go, and I'm trying to develop higher level interfaces for my code that ZeroMQ implements in order to support mocking in my tests.

As an example of my question, the zmq4.Socket struct's RecvMessage function expects a zmq4.Flag as an argument. zmq4.Flag is simply an int, as defined by type Flag int in the Go bindings.

I'm trying to develop my interfaces without any dependencies on the ZeroMQ bindings, so I have an interface defined as:

type Socket interface {
    RecvMessage(int) ([]string, error)
}

When I try to use a ZeroMQ socket for this interface, I get an error stating ... have RecvMessage(zmq4.Flag) ([]string, error) want RecvMessage(int) ([]string, error).

Is there any way to handle this, or do I just need to bite the bullet and depend on the ZeroMQ bindings in my interfaces?

答案1

得分: 4

重要的是要意识到type Foo int是一个独立的类型,而不是一个别名。
请参考https://stackoverflow.com/questions/19577423/how-to-cast-to-a-type-alias-in-go

要使用zmq4.Flag调用RecvMessage的唯一方法是将其转换为int。

var f zmq4.Flag = 1
RecvMessage(int(f))
英文:

It is important to realize that type Foo int is a separate type not an alias.
See https://stackoverflow.com/questions/19577423/how-to-cast-to-a-type-alias-in-go

The only thing you can do to call RecvMessage with zmq4.Flag is to convert it to int.

var f zmq4.Flag = 1
RecvMessage(int(f))

huangapple
  • 本文由 发表于 2016年1月15日 08:43:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/34802485.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定