0
0
Goprogramming~5 mins

Function parameters in Go

Choose your learning style9 modes available
Introduction

Function parameters let you send information into a function so it can use that information to do its job.

When you want a function to work with different values each time you call it.
When you want to reuse the same function but with different inputs.
When you want to organize your code by breaking tasks into smaller parts that need information.
When you want to avoid repeating code by passing data to functions.
When you want to make your functions flexible and easy to test.
Syntax
Go
func functionName(paramName paramType) returnType {
    // function body
}

Parameters are listed inside parentheses after the function name.

You can have multiple parameters separated by commas.

Examples
This function takes one parameter called name of type string.
Go
func greet(name string) {
    fmt.Println("Hello, " + name)
}
This function takes two int parameters and returns their sum.
Go
func add(a int, b int) int {
    return a + b
}
You can group parameters of the same type to write less code.
Go
func multiply(x, y int) int {
    return x * y
}
Sample Program

This program defines a function greet that takes a name and prints a greeting. In main, it calls greet twice with different names.

Go
package main

import "fmt"

func greet(name string) {
    fmt.Println("Hello, " + name + "!")
}

func main() {
    greet("Alice")
    greet("Bob")
}
OutputSuccess
Important Notes

Parameter names should be clear to show what data the function expects.

Parameters are local to the function and cannot be used outside it.

You can have functions with no parameters if they don't need extra information.

Summary

Function parameters let you send data into functions.

You list parameters inside parentheses after the function name.

Parameters make functions flexible and reusable with different inputs.