Go Functions
In Go, a function is a block of code that performs a specific task. Functions are the building blocks of Go programs, and they are used to encapsulate and organize code, making it easier to read, write, and maintain.
Here's the syntax for defining a function in Go:
func functionName(parameter1 type1, parameter2 type2) returnType { // function body return returnValue }
In this example, a function named functionName
is defined with two parameters parameter1
of type type1
and parameter2
of type type2
. The function returns a value of type returnType
, and its body is contained within the curly braces {}
.
Here's an example of a simple function that adds two numbers and returns the result:
func add(x int, y int) int { return x + y }
In this example, a function named add
is defined with two integer parameters x
and y
. The function returns the sum of the two parameters.
You can call a function by using its name followed by a pair of parentheses ()
that contain the arguments passed to the function. Here's an example of calling the add
function:
sum := add(3, 5) fmt.Println(sum) // prints 8
In this example, the add
function is called with arguments 3
and 5
, and its return value is assigned to a variable named sum
. The value of sum
is then printed to the console using the fmt.Println
function.
Go also supports functions with multiple return values, as well as functions that take variable numbers of arguments. Here's an example of a function that returns multiple values:
func swap(x, y string) (string, string) { return y, x } a, b := swap("hello", "world") fmt.Println(a, b) // prints "world hello"
In this example, a function named swap
is defined that takes two string parameters and returns them in reverse order. The function is called with the arguments "hello"
and "world"
, and its return values are assigned to the variables a
and b
. The values of a
and b
are then printed to the console.