所有数字的接口?

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

Interface for all numbers?

问题

在Go语言中,没有直接支持所有整数和浮点数类型的接口。在示例中,Number 接口使用了联合类型(Union Types)的语法,表示接受 int64float64 类型的值。这种方式可以实现对整数和浮点数类型的一定程度的抽象,但并不能涵盖所有可能的整数和浮点数类型。

英文:

The generics tutorial uses this:

type Number interface {
    int64 | float64
}

Is there no interface for all integer and float types in golang?

答案1

得分: 1

你可以声明一个新的类型约束,将constraints.Floatconstraints.Integer整合在一起。

// Number是一个自定义类型约束,扩展了实验性约束包中的Float和Integer类型约束。
type Number interface {
	constraints.Float | constraints.Integer
}
英文:

You can declare a new type constraint which integrates constraints.Float and constraints.Integer.

// Number is a custom type set of constraints extending the Float and Integer type set from the experimental constraints package.
type Number interface {
	constraints.Float | constraints.Integer
}

huangapple
  • 本文由 发表于 2022年6月10日 14:49:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/72570147.html
匿名

发表评论

匿名网友

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

确定