英文:
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))
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论