How are functions defined in Go?
In Go, functions are defined using the func keyword followed by the function name, a list of parameters enclosed in parentheses (), an optional return type, and a function body enclosed in curly braces {}. Here’s the general syntax for defining a function in Go:
go func functionName(parameter1 type1, parameter2 type2, ...) returnType { // Function body }
Functions in Go can have zero or more parameters and zero or more return values. The return type of a function is specified after the parameter list, separated by a space. If a function has multiple return values, they are enclosed in parentheses ().
Here’s an example of defining a simple function in Go:
go func add(x, y int) int { return x + y }
In this example, we define a function named add that takes two int parameters (x and y) and returns their sum as an int. Functions in Go are first-class citizens, meaning they can be assigned to variables, passed as arguments to other functions, and returned from other functions, enabling powerful functional programming techniques.