Parameters and return
- Go course
- Beginner
- Lesson 30/90
- 4 min
Learn to write functions with parameters and return values.
Parameters and return values
Parameters are always passed by copying (pass by value): changing a parameter inside the function doesn't affect the caller's variable.
func artir(n int) {
n++
}
x := 5
artir(x)
fmt.Println(x) // 5, unchangedTo have the change reach the caller, either return the new value or pass a pointer (you'll see this later).
The signature
A function's parameter and return types are its signature. Consecutive parameters of the same type are shortened: func alan(en, boy float64) float64. For an unused parameter, _ can be written instead of a name. Go has no default parameter values; every argument is given explicitly.
Practice Rectangle area
Write the alan(en, boy float64) float64 function and print the result of alan(3, 4.5).
Starter code
package main
import "fmt"
func main() {
// buraya yaz
}Sample solution
package main
import "fmt"
func alan(en, boy float64) float64 {
return en * boy
}
func main() {
fmt.Println(alan(3, 4.5))
}Expected output
13.5
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 After this call, what is <code>x</code>? <code>x := 5; x = ikiKat(x)</code> (ikiKat returns n*2)
- 10 Correct answer
- 5
- 0
- 25
Explanation: The function works on a copy but returns the result; assigning it to x makes x 10.
2 Shortened parameters
func alan(en, boy ____) float64 {
return en * boy
}
func alan(en, boy float64) float64 {
return en * boy
}
Explanation: For consecutive parameters of the same type, the type is written once at the end.
3 Concept
| Term | Meaning |
|---|---|
Pass by value |
A copy is taken |
Signature |
Parameter + return types |
_ parametresi |
An unused value |
Default value |
Not in Go |