Bryan
Bryan

Reputation: 2305

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

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?

Upvotes: 0

Views: 135

Answers (1)

kopiczko
kopiczko

Reputation: 3058

It is important to realize that type Foo int is a separate type not an alias. See 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))

Upvotes: 4

Related Questions