Kites
Kites

Reputation: 1168

How do I make an Interface that just allows integers?

I want to make a function that can take any int-like variable.

For example:

type IntegerType interface {
    int 
}

func MyFunc(arg IntegerType) {
    fmt.Println(arg)
}

This won't compile because I can't base interface inheritance on a non-interface type, but that's exactly what I want to do!

The end goal is this:

type Token int
var t Token
t = 3
MyFunc(t)

How do I guarantee that my argument is an integer, while still allowing integer aliases?

Upvotes: 1

Views: 139

Answers (1)

evanmcdonnal
evanmcdonnal

Reputation: 48096

How do I guarantee that my argument is an integer, while still allowing integer aliases?

You rely on type conversion.

func MyFunc(arg int) {
    fmt.Println(arg)
}

type Token int
var t Token
t = 3
MyFunc(int(t))

s := "This is a string, obviously"
MyFunc(int(s)) // throws a compiler error

There's really no need to define an interface for just the type int because you can rely on the languages type conversion behavior to enforce compile time type safety in these types of scenarios.

One thing to note is this is slightly more accepting than an int only interface would be. For example, an int64 will convert to a int, even a float will using typical rounding conventions. Invalid conversions will produce the following error; cannot convert s (type string) to type int. From what I can tell only native numeric types or aliases for them will convert.

Upvotes: 2

Related Questions