Functions are reusable blocks of code that perform specific tasks. In Go, functions help organize your program into logical parts and promote code reusability.
func functionName(parameters) returnType { // function body }
- func
keyword declares a function.
- parameters
are optional and specify inputs.
- returnType
is optional and specifies the type of value the function returns.
func greet() { fmt.Println("Hello, welcome to Go functions!") } func main() { greet() }
func add(a int, b int) { fmt.Println("Sum:", a + b) } func main() { add(10, 20) }
func multiply(x int, y int) int { return x * y } func main() { result := multiply(5, 7) fmt.Println("Product:", result) }
Go supports returning multiple values from a function, useful in many scenarios like returning results and errors together.
func swap(a, b string) (string, string) { return b, a } func main() { x, y := swap("hello", "world") fmt.Println(x, y) // Output: world hello }
You can name the return values in the function signature and then simply use return
without specifying variables.
func divide(a, b float64) (result float64, err error) { if b == 0 { err = fmt.Errorf("cannot divide by zero") return } result = a / b return } func main() { res, err := divide(10, 0) if err != nil { fmt.Println("Error:", err) } else { fmt.Println("Result:", res) } }
func
keyword.Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!