In Go, a simple function can be defined using the func
keyword. Functions in Go can have parameters and can return values.
Here is an example of a simple function that takes two integers as parameters and returns their sum:
package main import "fmt" func sum(a, b int) int { return a + b } func main() { result := sum(5, 3) fmt.Println(result) // Output: 8 }
In the above code, we define a function called sum
that takes two integer parameters a
and b
. Inside the function, we simply return the sum of a
and b
.
In the main
function, we call the sum
function with arguments 5
and 3
and store the result in the result
variable. Finally, we print the result using the fmt.Println
function.
Functions in Go can also have multiple return values. Here is an example of a function that calculates both the sum and difference of two integers:
package main import "fmt" func sumAndDiff(a, b int) (int, int) { return a + b, a - b } func main() { sumResult, diffResult := sumAndDiff(5, 3) fmt.Println(sumResult) // Output: 8 fmt.Println(diffResult) // Output: 2 }
In the sumAndDiff
function, we use the (int, int)
syntax to specify that the function returns two integer values. Inside the function, we calculate the sum and difference of the two parameters and return them as separate values.
In the main
function, we call the sumAndDiff
function and store the results in two separate variables sumResult
and diffResult
. Then, we print both results using the fmt.Println
function.
These examples demonstrate the basics of defining and using simple functions in Go. Functions are a fundamental building block in Go and are used extensively in developing complex applications.