Golang为什么没有整型的max/min方法
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的设计原则,尽可能保持简洁干净。
Recommend
-
9
[笔记] awk命令计算sum, min, max, avg
-
8
了解CSS min()/max()/clamp()数学函数 这篇文章发布于 2020年04月12日,星期日,23:29,归类于 CSS相关。 阅读 13304 次, 今日 11 次...
-
8
by zhangxinxu from https://www.zhangxinxu.com 本文地址:https://www.zhangxinxu.com/wordpress/?p=5...
-
4
Do we correctly calculate min and max? Sandor Dargo 2 days ago2021-09-08T00:00:00+02:00This article is inspired by Walter E Brown’s talk at the Ital...
-
4
Using Min Medium Max Principles for iOS Design // Written by Jordan Morgan // Apr 18th, 2022...
-
7
Min-Max-Value Interpolation Min-Max-Value Interpolation View on GitHub ...
-
1
Weramajstor's blog Min Cost Max...
-
5
Let's say we have an array of users, but each user is also an array. For the example, we'll use the following data. const users = [ ['Nicole', 31], ['Chris', 33], ['Yaatree',...
-
0
Day 33: Mathematical expressions in min(), max(), clamp() posted on November 9., 2022 It’s time to get me up to speed with modern CSS. There’s so much new in CSS that I...
-
4
[Submitted on 6 Dec 2022] Online Min-Max Paging Download PDF Mot...
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK