2019-08-25 19:05
浏览 1.5k


In go, why there is no function which directly calculates absolute value for integer datatypes. Currently all integer values has to be type casted to float64 and then it has to be used as a parameter in math.Abs() function. And it returns float64 datatype only, which again has to be type casted into integer datatype.

Like this code is giving error as Go is statically typed language, so does not allows different datatype.

./prog.go:12:39: cannot use x (type int64) as type float64 in argument to math.Abs

import (

func main() {
    fmt.Println("Hello, playground")
    var x int64 = -10

    fmt.Println("Abolute value ",math.Abs(x))   

图片转代码服务由CSDN问答提供 功能建议

在旅途中,为什么没有直接为整数数据类型计算绝对值的函数。 当前,所有整数值都必须类型转换为float64,然后必须用作math.Abs​​()函数中的参数。 并且它仅返回float64数据类型,再次必须将其类型转换为整数数据类型。

就像该代码给了错误一样,因为Go是静态类型的语言,因此不允许使用其他数据类型。 / p>

./ prog.go:12:39:不能在数学\ Abs的参数 中使用x(int64类型)作为float64类型 / blockquote>

“ fmt” 
func main(){
 fmt.Println(“ H​​ello,Playground”)\  n var x int64 = -10 
 fmt.Println(“ Abolute value”,math.Abs​​(x))
  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • doujie4787 2019-08-25 20:35

    From Go's FAQ,

    The standard library's purpose is to support the runtime, connect to the operating system, and provide key functionality that many Go programs require, such as formatted I/O and networking. It also contains elements important for web programming, including cryptography and support for standards like HTTP, JSON, and XML.

    There is no clear criterion that defines what is included because for a long time, this was the only Go library. There are criteria that define what gets added today, however.

    New additions to the standard library are rare and the bar for inclusion is high. Code included in the standard library bears a large ongoing maintenance cost (often borne by those other than the original author), is subject to the Go 1 compatibility promise (blocking fixes to any flaws in the API), and is subject to the Go release schedule, preventing bug fixes from being available to users quickly.

    Most new code should live outside of the standard library and be accessible via the go tool's go get command. Such code can have its own maintainers, release cycle, and compatibility guarantees. Users can find packages and read their documentation at godoc.org.

    In response to how easy it is to create integer versions of the math package's float functions, Go team member Russ Cox once quipped,

    Ceil, Floor, and Trunc are even easier!

    A reasonable interpretation would be that since this function is trivial to write (if x < 0, x = -x), it does not meet the bar for inclusion. Compare with the float version:

    func Abs(x float64) float64 {
        return Float64frombits(Float64bits(x) &^ (1 << 63))

    This being useful but also not obvious is a compelling reason to include it in the standard library.

    解决 无用
    打赏 举报

相关推荐 更多相似问题