如何创建一个只允许整数的界面?

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

How do I make an Interface that just allows integers?

问题

我想创建一个可以接受任何类似整数的变量的函数。

例如:

type IntegerType interface {
    int 
}

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

这段代码无法编译,因为我不能基于非接口类型进行接口继承,但这正是我想要做的!

最终目标是:

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

我该如何确保我的参数是一个整数,同时仍然允许整数的别名?

英文:

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?

答案1

得分: 2

如何确保我的参数是整数,同时允许整数别名?

你可以依赖类型转换来实现。

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)) // 报编译错误

在这种情况下,其实没有必要为类型int定义一个接口,因为你可以依赖语言的类型转换行为来在编译时强制执行类型安全。

需要注意的是,这种方式比仅限于int类型的接口要宽松一些。例如,int64会转换为int,甚至float也会按照典型的舍入规则进行转换。无效的转换会产生以下错误:cannot convert s (type string) to type int。据我所知,只有原生的数值类型或其别名才能进行转换。

英文:

> 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.

huangapple
  • 本文由 发表于 2015年7月9日 23:55:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/31322541.html
匿名

发表评论

匿名网友

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

确定