Go Function Parameters

Passing data to functions in Go

📥 What are Function Parameters?

Function parameters allow you to pass data into functions, making them flexible and reusable. Parameters act as variables that receive values when the function is called.


// Function with parameters
func greet(name string) {
    fmt.Println("Hello,", name)
}

func main() {
    greet("Alice") // Pass "Alice" as argument
}
                                    

Output:

Hello, Alice

Key Parameter Concepts

📝

Declaration

Define parameters with name and type

func add(a int, b int) {
    // a and b are parameters
}
🎯

Arguments

Values passed when calling function

add(5, 3) // 5 and 3 are arguments
🔄

Multiple

Functions can have multiple parameters

func info(name string, age int) {
    // Two parameters
}
📊

Types

Each parameter must have a type

func calc(x float64, y int) {
    // Different types
}

🔹 Single Parameter Functions

Functions with one parameter:

package main

import "fmt"

// Function with string parameter
func sayHello(name string) {
    fmt.Println("Hello,", name)
}

// Function with integer parameter
func square(number int) {
    result := number * number
    fmt.Println("Square of", number, "is", result)
}

func main() {
    sayHello("Bob")
    square(4)
}

Output:

Hello, Bob

Square of 4 is 16

🔹 Multiple Parameter Functions

Functions can accept multiple parameters:

package main

import "fmt"

// Function with multiple parameters
func add(a int, b int) int {
    return a + b
}

// Function with different parameter types
func introduce(name string, age int, height float64) {
    fmt.Printf("Name: %s, Age: %d, Height: %.1f\n", name, age, height)
}

func main() {
    sum := add(10, 20)
    fmt.Println("Sum:", sum)
    
    introduce("Charlie", 25, 5.8)
}

Output:

Sum: 30

Name: Charlie, Age: 25, Height: 5.8

🔹 Parameter Type Shorthand

When parameters have the same type, you can use shorthand:

package main

import "fmt"

// Long form
func multiply1(a int, b int, c int) int {
    return a * b * c
}

// Short form - same type parameters
func multiply2(a, b, c int) int {
    return a * b * c
}

// Mixed types
func calculate(x, y int, rate float64) float64 {
    return float64(x+y) * rate
}

func main() {
    result1 := multiply1(2, 3, 4)
    result2 := multiply2(2, 3, 4)
    result3 := calculate(10, 5, 1.5)
    
    fmt.Println("Result 1:", result1)
    fmt.Println("Result 2:", result2)
    fmt.Println("Result 3:", result3)
}

Output:

Result 1: 24

Result 2: 24

Result 3: 22.5

🧠 Test Your Knowledge

What is the correct way to declare a function with two integer parameters?