Functions
Go Functions
Defining Go Functions
Go functions use func with typed parameters and returns.
Introduction to Go Functions
Functions in Go are a core concept that allows you to group code into reusable blocks. They are defined using the func
keyword, and they can accept parameters and return values. Each parameter and return value in Go must be explicitly typed, which helps prevent errors and makes the code more readable.
Defining a Basic Function
A simple function in Go is defined using the func
keyword, followed by the function name, a list of parameters, and a return type. Here's a basic example:
Function Parameters and Return Types
In Go, function parameters are listed in parentheses following the function name. Each parameter must have a type. If multiple parameters share the same type, you can list them together and specify the type once. Functions can return zero or more values, and each return value must also have a type.
Named Return Values
Go supports named return values. This feature allows you to name the return values in the function signature. These names can be used as variables within the function, and the return
statement can be omitted to return the named values.
Variadic Functions
Go functions can also accept a variable number of arguments, known as variadic functions. To define a variadic function, use an ellipsis (...
) before the parameter type. The variadic parameter is treated as a slice of that type.
In this example, you can pass any number of integers to the sum
function, and it will return their total.
Functions
- Previous
- panic and recover
- Next
- Multiple Returns