0
0
Goprogramming~5 mins

Function declaration in Go

Choose your learning style9 modes available
Introduction

Functions help you organize your code into small, reusable pieces. They make your program easier to read and use.

When you want to repeat a task multiple times without rewriting code.
When you want to break a big problem into smaller, manageable parts.
When you want to give a name to a set of instructions for clarity.
When you want to reuse code in different parts of your program.
When you want to test parts of your program separately.
Syntax
Go
func functionName(parameters) returnType {
    // code to run
}

func starts the function declaration.

Parameters are optional; return type is also optional if the function returns nothing.

Examples
A simple function with no parameters and no return value.
Go
func greet() {
    fmt.Println("Hello!")
}
A function that takes two numbers and returns their sum.
Go
func add(a int, b int) int {
    return a + b
}
Parameters can share the same type if they are the same.
Go
func multiply(x, y int) int {
    return x * y
}
Sample Program

This program declares two functions: greet prints a message, and add returns the sum of two numbers. The main function calls both.

Go
package main

import "fmt"

func greet() {
    fmt.Println("Hello, friend!")
}

func add(a int, b int) int {
    return a + b
}

func main() {
    greet()
    sum := add(3, 4)
    fmt.Println("Sum is", sum)
}
OutputSuccess
Important Notes

Function names should start with a letter and use camelCase style.

Functions can return multiple values in Go, but here we show a simple single return.

Use func keyword to declare functions.

Summary

Functions group code to do one job.

Use func keyword to declare them.

Functions can have parameters and return values.