- Basic Function Syntax
func functionName(parameters) returnType { // function body }
Example:
func greet(name string) string { return "Hello, " + name }
- Calling a Function
message := greet("Alice") fmt.Println(message) // Output: Hello, Alice
- Multiple Parameters
func add(a int, b int) int { return a + b }
Shortcut: Same type for multiple parameters:
func add(a, b int) int { return a + b }
- Multiple Return Values
func divide(dividend, divisor float64) (float64, string) { if divisor == 0 { return 0, "Error: Division by zero" } return dividend / divisor, "Success" }
result, status := divide(10, 2)
- Named Return Values You can give names to return values — useful in longer functions.
func getFullName() (firstName, lastName string) { firstName = "John" lastName = "Doe" return // implicit return }
- Variadic Functions (accept any number of arguments)
func sum(nums ...int) int { total := 0 for _, num := range nums { total += num } return total }
sum := sum(1, 2, 3, 4, 5) // Output: 15
- Anonymous Functions Functions without names, used for short tasks or inline.
func() { fmt.Println("I am anonymous") }()
Or assign to a variable:
greet := func(name string) string { return "Hello, " + name } fmt.Println(greet("Bob"))
- Closures (Function with Access to Outer Variables)
func counter() func() int { count := 0 return func() int { count++ return count } } next := counter() fmt.Println(next()) // 1 fmt.Println(next()) // 2
- Function as Parameter
func process(name string, f func(string) string) string { return f(name) } func shout(s string) string { return strings.ToUpper(s) } result := process("hello", shout)
- Scope in Go
- Local scope: Variables declared inside a function are only accessible there.
- Global scope: Variables declared outside of all functions are accessible everywhere in the same package.
- Block scope: Variables inside {} are scoped to that block.
var globalVar = "I’m global" func example() { localVar := "I’m local" fmt.Println(globalVar, localVar) }
- Return Early (Best Practice) Avoid deep nesting using early returns:
func login(user string) string { if user == "" { return "No user provided" } return "Welcome " + user }
- Recursive Function A function that calls itself:
func factorial(n int) int { if n == 0 { return 1 } return n * factorial(n-1) }
Top comments (0)