How to create and use functions in Go?

To create and use functions in Go, you can follow these steps:

  1. Function Declaration: Start by declaring a function using the func keyword followed by the function name, parameter list, and return type. For example:
func sayHello() { fmt.Println("Hello!") }
  1. Function Parameters and Return Types: You can define parameters within parentheses after the function name, separated by commas. And if your function returns a value, specify the return type after the parameter list using the func functionName() returnType syntax. For example:
func sum(a int, b int) int { return a + b }
  1. Function Call: To call a function, simply use its name followed by parentheses. For example:
sayHello() // Call the sayHello function result := sum(10, 5) // Call the sum function and store the result fmt.Println(result)
  1. Function Arguments: When calling a function with parameters, pass the arguments inside the parentheses separated by commas. For example:
func printMessage(message string) { fmt.Println(message) } printMessage("Hello, World!") // Call the printMessage function with an argument
  1. Function Multiple Return Values: Go functions can return multiple values. For example:
func calculate(a, b int) (int, int) { return a + b, a - b } sum, diff := calculate(10, 5) // Call the calculate function and use multiple return values fmt.Println(sum, diff)

Note that you need to import the necessary packages to use built-in functions from the Go standard library.