math.Abs只接受float64或float32,不支持整数;传入int会编译报错,需显式转换为float64或float32;整数求绝对值需用条件判断或自定义函数。

math.Abs 返回与输入参数相同类型的浮点数,具体是 float64 或 float32,取决于你传入的是哪种浮点类型。
math.Abs 只接受 float64 和 float32
Go 标准库中的 math.Abs 是重载函数(实际是两个独立函数),分别定义为:
func Abs(x float64) float64-
func Abs(x float32) float32(在math包中,需显式调用math.Abs(float32(x)))
注意:它不接受整数类型(如 int、int64)。如果传入整数,会编译报错 —— Go 不会自动把整数转成浮点数。
常见误用:直接传 int 会报错
比如下面代码无法通过编译:
立即学习“go语言免费学习笔记(深入)”;
❌ 错误示例:math.Abs(-5) → 报错:cannot use -5 (type untyped int) as type float64 in argument to math.Abs
正确写法是先显式转换:
-
math.Abs(float64(-5))→ 返回5.0(类型float64) -
math.Abs(float32(-5))→ 返回5.0(类型float32)
整数绝对值怎么办?用内置函数或自己写
Go 没有提供泛型版的 Abs(直到 Go 1.18+ 泛型可用,但标准库仍未更新),所以对整数通常:
- 用条件判断:
if x - 用
int(math.Abs(float64(x)))(注意溢出和精度风险,不推荐大整数) - Go 1.21+ 可用
constraints.Integer+ 自定义泛型函数(需自己实现)
基本上就这些。记住核心:math.Abs 不是“万能类型转换器”,它只认浮点数,返回同类型浮点数。










