alt
codecamp
Golang Essentials: Functions
Previous
Next
☰
About
Profile
Account
Login
Sign Up
Logout
Run
Test
Mark Complete
## Functions In Go, a function is defined using the func keyword, followed by the function's name, the parameter list (enclosed in parentheses), the return type, and finally the function body enclosed in curly braces. Functions can accept zero or more parameters and may return zero or more values. Basic Syntax The basic syntax for writing a function in Go is: ```go // Adds two integers and returns the result func add(a int, b int) int { return a + b } ``` In this example, add is a function that takes two parameters, a and b, both of type int, and returns an integer, which is the sum of a and b. ## Multiple Return Values Go functions can return multiple values, which is a distinctive feature of the language. Here's an example: ```go // Divides two integers and returns the result and remainder func divide(a int, b int) (int, int) { result := a / b remainder := a % b return result, remainder } ``` This function, divide, takes two integer parameters and returns two integers: the result of the division and the remainder. ## Named Return Values Go also supports named return values. Here's an example using named return values: ```go // Calculates the square and cube of a number func squareAndCube(a int) (square int, cube int) { square = a * a cube = a * a * a return } ``` In this example, squareAndCube returns two named values: square and cube. The return statement does not need to specify the return values explicitly since they are named. ## Conclusion Writing functions in Go is straightforward. By understanding the syntax and features like multiple return values and named return values, you can effectively utilize functions to organize and structure your Go code.