Go Parameters and Arguments 🎯

beginner
18 min

Go Parameters and Arguments 🎯

Welcome to another exciting lesson on Go Programming! Today, we're going to dive into the world of Parameters and Arguments. 💡

Understanding Parameters and Arguments 📝

In simple terms, parameters are variables that are defined within a function. They are placeholders that represent values to be passed into a function when it's called. On the other hand, arguments are the values that are actually passed when a function is invoked.

Let's see this in action with a simple example:

go
package main import "fmt" func greet(name string) { fmt.Println("Hello,", name) } func main() { greet("Alice") }

In the above code, name is the parameter of the greet function, and "Alice" is the argument we pass to the function in the main function.

Function Parameters 📝

Go supports various types of parameters, including:

  1. Values: These are simple variables passed by value.
  2. Pointers: These are variables passed by reference.
  3. Slices: These are dynamic arrays passed as a single entity.

Value Parameters

Value parameters are passed by value, which means a copy of the value is passed to the function. Changes made to the parameter inside the function do not affect the original value.

go
package main import "fmt" func increment(x int) { x += 1 } func main() { num := 5 increment(num) fmt.Println(num) // Output: 5 }

Pointer Parameters

Pointer parameters are passed by reference. This means the memory address of the variable is passed to the function, allowing changes made to the parameter inside the function to reflect on the original value.

go
package main import "fmt" func incrementPointer(x *int) { *x += 1 } func main() { num := 5 incrementPointer(&num) fmt.Println(num) // Output: 6 }

Slice Parameters

When a slice is passed as an argument, it is passed as a pointer. This means changes made to the slice inside the function affect the original slice.

go
package main import "fmt" func changeSlice(s []int) { s[0] = 100 } func main() { numbers := []int{1, 2, 3} changeSlice(numbers) fmt.Println(numbers) // Output: [100 2 3] }

Function Arguments 📝

Function arguments are the values we pass when calling a function. They can be values, pointers, or slices.

When calling a function, the number and types of arguments must match the number and types of parameters defined in the function signature.

Quiz 💡

Quick Quiz
Question 1 of 1

What happens when we pass a slice as an argument to a function in Go?

That's it for today! In the next lesson, we'll explore Go's control structures, which will help us to write more complex programs. Until then, happy coding! ✅