31

Golang为什么没有整型的max/min方法

 4 years ago
source link: https://studygolang.com/articles/25200
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

作为有一些经验的Golang开发者,你可能意识到了Golang并没有max/min方法来返回给定的两个或多个整型数值中的最大值或最小值。其他语言通常会在核心库中提供这类方法。 你有没有想过为什么Golang没有这么做?

Golang确实在 math 包中提供了max/min方法,但是仅用于对比float64类型。方法的签名如下:

math.Min(float64, float64) float64
math.Max(float64, float64) float64

Golang为float64提供max/min方法是浮点类型的比较对于大部分开发者来说比较困难。由于涉及精度问题,浮点数的对比往往没有那么直接。所以Golang在 math 包中提供了用于浮点数对比的内建方法。

对于int/int64数据类型来说,max/min方法的实现就相当简单了,任何有基础编程经验的开发者都可以轻松的实现这两个方法:

func Min(x, y int64) int64 {
 if x < y {
   return x
 }
 return y
}

func Max(x, y int64) int64 {
 if x > y {
   return x
 }
 return y
}

另外,为了尽可能保持Golang简洁干净,Golang并不支持泛型。所以既然已经有了对比float64数据类型的max/min方法,在同一个 math 包中就无法支持同名的但是参数类型不同的方法。也就是说下面的方法无法存在同一个包中。

math.Max(float64, float64) float64
math.Max(int64, int64) int64

这也符合Golang的设计原则,尽可能保持简洁干净。

原文: Why no max/min function for integer in GoLang


Recommend

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK