func declaration
- Go course
- Beginner
- Lesson 29/90
- 4 min
Learn to declare functions with the func keyword.
Defining functions
A function is defined with the func keyword: the name, parameters in parentheses, then the return type and the body in curly braces.
func selam(ad string) string {
return "Merhaba " + ad
}
fmt.Println(selam("Ada")) // Merhaba AdaFunctions starting with an upper-case letter (Selam) can be called from outside the package; lower-case ones only within it.
Why functions?
Writing repeated code once and calling it by name reduces mistakes and makes reading easier. A good function does one job and its name describes it: kdvEkle, ortalama, gecerliMi. In Go, functions can't be defined inside other functions (except anonymous ones), and there is no overloading (same name, different parameters).
Practice Square function
Write the kare(n int) int function and print the result of kare(7).
Starter code
package main
import "fmt"
func main() {
// buraya yaz
}Sample solution
package main
import "fmt"
func kare(n int) int {
return n * n
}
func main() {
fmt.Println(kare(7))
}Expected output
49
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does a function with no return type return?
- It doesn't compile
- Nothing; its return statement takes no value Correct answer
- 0
- nil
Explanation: Functions like func yaz(s string) { fmt.Println(s) } return no value; a bare return is used to leave early.
2 Return a value
func kare(n int) int {
____ n * n
}
func kare(n int) int {
return n * n
}
Explanation: return gives the function's result to the caller.
3 Function part
| Term | Meaning |
|---|---|
func |
Definition keyword |
(ad string) |
Parameter |
string (after the parentheses) |
Return type |
return |
Gives the result |