CodeBlanks Logo Icon CodeBlanks

func declaration

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 Ada

Functions 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

main.go
package main

import "fmt"

func main() {
    // buraya yaz
}

Sample solution

main.go
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

Question
func kare(n int) int {
    ____ n * n
}
Answer
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

All lessons in Beginner