Golang Tutorial

Fundamentals

Control Statements

Functions & Methods

Structure

Arrays & Slices

String

Pointers

Interfaces

Concurrency

Function Arguments in Golang

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.

1. Basic Function Arguments

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
}

2. Multiple Arguments of the Same Type

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
}

3. Passing Slices and Arrays

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]
}

4. Variadic Functions

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
}

5. Passing Functions as Arguments

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]
}

6. Named Return Values

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
}

Conclusion

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.

  1. Passing Parameters to Functions in Golang:

    • Functions in Golang accept parameters, allowing data to be passed to them.
    • Example:
      package main
      
      import "fmt"
      
      func greet(name string) {
          fmt.Println("Hello, " + name + "!")
      }
      
      func main() {
          greet("Alice")
      }
      
  2. Variadic Functions in Golang with Examples:

    • Variadic functions accept a variable number of arguments.
    • Example:
      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)
      }
      
  3. Named Return Values and Function Arguments in Golang:

    • Named return values in functions enhance code readability.
    • Example:
      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)
      }
      
  4. Function Arguments and Their Scope in Golang:

    • Function arguments have local scope within the function.
    • Example:
      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)
      }
      
  5. Passing Pointers as Function Arguments in Golang:

    • Passing pointers allows modifying the original data.
    • Example:
      package main
      
      import "fmt"
      
      func updateValueByReference(value *int) {
          *value = *value * 2
      }
      
      func main() {
          x := 10
          updateValueByReference(&x)
          fmt.Println("Updated value:", x)
      }
      
  6. Default Values for Function Parameters in Golang:

    • Golang does not support default values for function parameters.
    • Use variadic functions or function overloading for similar effects.
    • Example (using variadic parameters):
      package main
      
      import "fmt"
      
      func greet(message string, names ...string) {
          for _, name := range names {
              fmt.Println(message, name)
          }
      }
      
      func main() {
          greet("Hello", "Alice", "Bob")
      }
      
  7. Multiple Return Values and Function Arguments in Golang:

    • Functions can return multiple values.
    • Example:
      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)
      }
      
  8. Using Interfaces as Function Arguments in Golang:

    • Functions can accept interfaces as parameters for flexibility.
    • Example:
      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)
      }
      
  9. Function Argument Validation in Golang:

    • Golang lacks built-in support for function argument validation.
    • Manually check and handle invalid inputs within the function.
    • Example:
      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)
          }
      }