Home >Backend Development >Golang >How Can a Golang Function Compile Without a Body?

How Can a Golang Function Compile Without a Body?

Linda Hamilton
Linda HamiltonOriginal
2024-12-29 01:30:10963browse

How Can a Golang Function Compile Without a Body?

Bodiless Functions in Golang

In the source code of math/floor.go, a function named Floor is declared without a body. The code snippet is as follows:

func Floor(x float64) float64

func floor(x float64) float64 {
    if x == 0 || IsNaN(x) || IsInf(x, 0) {
        return x
    }
    if x < 0 {
        d, fract := Modf(-x)
        if fract != 0.0 {
            d = d + 1
        }
        return -d
    }
    d, _ := Modf(x)
    return d
}

Despite the missing body, the Floor function compiles successfully. This is because functions in Go can be implemented outside the language itself, such as in assembly. The assembly implementation for floor can be found in files like floor_ARCH.s (e.g., AMD64).

The Go language specification allows for function declarations without bodies:

A function declaration may omit the body. Such a declaration provides the signature for a function implemented outside Go, such as an assembly routine.

The above is the detailed content of How Can a Golang Function Compile Without a Body?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn