0
0
Goprogramming~3 mins

Why Function parameters in Go? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if you could write one instruction that works for many different tasks just by changing a few details?

The Scenario

Imagine you want to bake a cake and write down every single step for each cake size separately. For a small cake, you write one recipe; for a big cake, another. You repeat almost the same instructions but change the amounts manually each time.

The Problem

This manual way is slow and confusing. If you want to change the baking time or ingredients, you must update every recipe separately. It's easy to make mistakes or forget one, leading to inconsistent cakes.

The Solution

Function parameters let you write one recipe that accepts the cake size as input. You just tell the function the size, and it adjusts the ingredients and baking time automatically. This saves time and avoids errors.

Before vs After
Before
func bakeSmallCake() {
  // ingredients for small cake
  // bake for 30 minutes
}
func bakeBigCake() {
  // ingredients for big cake
  // bake for 60 minutes
}
After
func bakeCake(size string) {
  if size == "small" {
    // ingredients for small cake
    // bake for 30 minutes
  } else if size == "big" {
    // ingredients for big cake
    // bake for 60 minutes
  }
}
What It Enables

Function parameters let you create flexible, reusable code that works for many situations by just changing inputs.

Real Life Example

When building a calculator app, you can write one function to add numbers, and by passing different numbers as parameters, it adds any two numbers without rewriting code.

Key Takeaways

Function parameters let you customize how a function works without rewriting it.

They save time and reduce mistakes by avoiding repeated code.

Parameters make your code flexible and easier to maintain.