Menu
Coddy logo textTech

Function Parameters

Lesson 5 of 19 in Coddy's Functions and Pointers in Golang course.

In the last lesson, we wrote our first function, which is a simple function that doesn't take any parameters; it just prints a message to the screen.

Now, let's say, for example, that we want to create a function that calculates the sum of two values. How can we do that? Well, we can do it like this:

func sum() {
    fmt.Println("result = ", value1 + value2)
}

You should understand this easily, right? We just do an addition of two values here and print the result. But we do have a problem here: value1 and value2 are not defined. How will this function know which values to sum? Here comes arguments or parameters. In between parentheses, we put parameters that this function will take, like this:

func sum(v1, v2 int) {
    fmt.Println("result =", v1+v2)
}

With this syntax sum(v1, v2 int), we mean that this function will take two values of type int, and we can do whatever we need with them inside the body of the function. In our case, we just print the addition of the two values fmt.Println("result = ", v1 + v1).

Now, when we call this function, we will pass two values as we like, and the function will calculate the sum for us:

func main() {
    sum(12, 44)
}

The output will be:

result = 56

And we can call this as we like. For example:

func main() {
    sum(12, 44)
    sum(100, 399)
}

The output will be:

result = 56
result = 400

Here, we just did an example of an integer type, but the parameters can be of any type depending on the situation. We can also put different types in one function, for example:

functionName(v1 int, v2 string)
challenge icon

Challenge

Easy

Write a function called coddy that takes two arguments s of type string and n of type int and prints to the screen the string s n times.

Example:

Input: s = "Golang" and n = 2

Output:

Golang
Golang

Try it yourself

import "fmt"

// Your Code Here

All lessons in Functions and Pointers in Golang