Golang Tutorial
Fundamentals
Control Statements
Functions & Methods
Structure
Arrays & Slices
String
Pointers
Interfaces
Concurrency
Function arguments are a fundamental concept in any programming language. In Go, they have certain specifics due to the language's type system and conventions. This tutorial will guide you through how to use function arguments in Go.
In Go, you define a function with the func
keyword, followed by the function's name, a list of arguments inside parentheses, and the return type (if any).
package main import "fmt" // A function with two arguments: x and y of type int. func add(x int, y int) int { return x + y } func main() { result := add(3, 4) fmt.Println(result) // Outputs: 7 }
If consecutive arguments are of the same type, you can omit the type for all but the last of those arguments.
func subtract(x, y int) int { return x - y }
Slices and arrays can be passed as arguments to functions. However, remember that slices are reference types (they point to an underlying array), so if you modify the slice inside the function, the changes will be visible outside. In contrast, arrays are value types and a copy is passed to the function.
func modifySlice(s []int) { s[0] = 100 } func modifyArray(a [3]int) { a[0] = 100 } func main() { slice := []int{1, 2, 3} array := [3]int{1, 2, 3} modifySlice(slice) modifyArray(array) fmt.Println(slice) // Outputs: [100 2 3] fmt.Println(array) // Outputs: [1 2 3] }
Go supports variadic functions, which can accept a variable number of arguments. This is done using the ...
syntax before the type of the last parameter.
func sum(numbers ...int) int { total := 0 for _, num := range numbers { total += num } return total } func main() { fmt.Println(sum(1, 2)) // Outputs: 3 fmt.Println(sum(1, 2, 3, 4)) // Outputs: 10 }
In Go, functions are first-class citizens, which means you can pass them as arguments to other functions.
func apply(nums []int, op func(int) int) []int { result := make([]int, len(nums)) for i, n := range nums { result[i] = op(n) } return result } func square(x int) int { return x * x } func main() { numbers := []int{1, 2, 3, 4} squaredNumbers := apply(numbers, square) fmt.Println(squaredNumbers) // Outputs: [1 4 9 16] }
Go supports named return values. They can serve as documentation, and they're assigned a zero value by default. You can use the return
keyword without explicitly mentioning the return value if you've named them.
func split(sum int) (x, y int) { x = sum * 4 / 9 y = sum - x return } func main() { fmt.Println(split(18)) // Outputs: 8 10 }
Function arguments in Go can range from simple to complex types. By understanding the different ways to pass and manipulate arguments, you can write more flexible and maintainable Go code. Remember always to consider the implications of passing value vs. reference types to functions to avoid unexpected side effects.
Passing Parameters to Functions in Golang:
package main import "fmt" func greet(name string) { fmt.Println("Hello, " + name + "!") } func main() { greet("Alice") }
Variadic Functions in Golang with Examples:
package main import "fmt" func sum(numbers ...int) int { result := 0 for _, num := range numbers { result += num } return result } func main() { total := sum(1, 2, 3, 4, 5) fmt.Println("Sum:", total) }
Named Return Values and Function Arguments in Golang:
package main import "fmt" func addAndMultiply(a, b int) (sum, product int) { sum = a + b product = a * b return } func main() { resultSum, resultProduct := addAndMultiply(3, 4) fmt.Println("Sum:", resultSum, "Product:", resultProduct) }
Function Arguments and Their Scope in Golang:
package main import "fmt" func updateValue(value int) { value = value * 2 fmt.Println("Inside function:", value) } func main() { x := 10 updateValue(x) fmt.Println("Outside function:", x) }
Passing Pointers as Function Arguments in Golang:
package main import "fmt" func updateValueByReference(value *int) { *value = *value * 2 } func main() { x := 10 updateValueByReference(&x) fmt.Println("Updated value:", x) }
Default Values for Function Parameters in Golang:
package main import "fmt" func greet(message string, names ...string) { for _, name := range names { fmt.Println(message, name) } } func main() { greet("Hello", "Alice", "Bob") }
Multiple Return Values and Function Arguments in Golang:
package main import "fmt" func divideAndRemainder(a, b int) (int, int) { quotient := a / b remainder := a % b return quotient, remainder } func main() { q, r := divideAndRemainder(10, 3) fmt.Println("Quotient:", q, "Remainder:", r) }
Using Interfaces as Function Arguments in Golang:
package main import "fmt" type Shape interface { Area() float64 } func printArea(s Shape) { fmt.Println("Area:", s.Area()) } func main() { // Implement a type that satisfies the Shape interface type Circle struct { Radius float64 } // Implement the Area method for Circle func (c Circle) Area() float64 { return 3.14 * c.Radius * c.Radius } circle := Circle{Radius: 2.5} printArea(circle) }
Function Argument Validation in Golang:
package main import ( "fmt" "errors" ) func divide(a, b int) (int, error) { if b == 0 { return 0, errors.New("division by zero") } return a / b, nil } func main() { result, err := divide(10, 0) if err != nil { fmt.Println("Error:", err) } else { fmt.Println("Result:", result) } }