Welcome to another exciting lesson on Go Programming! Today, we're going to dive into the world of 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:
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.
Go supports various types of parameters, including:
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.
package main
import "fmt"
func increment(x int) {
x += 1
}
func main() {
num := 5
increment(num)
fmt.Println(num) // Output: 5
}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.
package main
import "fmt"
func incrementPointer(x *int) {
*x += 1
}
func main() {
num := 5
incrementPointer(&num)
fmt.Println(num) // Output: 6
}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.
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 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.
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! ✅