search

What is the difference between Go's short and long form of function declaration syntax?

In Go, there are two forms of function declaration syntax: short form and long form.

The short form is used to declare and define a function at the same time. It uses the **func** keyword followed by the function name, its parameters (if any), and its return type (if any), followed by the function body enclosed in curly braces. Here's an example:

func add(a, b int) int {
    return a + b
}

The long form is used to declare a function signature separately from its definition. It is often used when defining functions that take functional arguments or to make a type definition implement an interface. It uses the **func** keyword followed by the function name, its parameters (if any), and its return type (if any), but without the function body. Here's an example:

func add(a, b int) int

// later in the code...
func add(a, b int) int {
    return a + b
}

In the long form, the function signature is followed by a semicolon instead of the function body. The function body is defined later in the code block, and it must match the signature declared earlier.

Related Questions You Might Be Interested