CodeBlanks Logo Icon CodeBlanks

Summary - Functions

Use multiple return and variadic parameters to write a helper.

Functions summary

In this group you learned the func name(parameters) result syntax, pass by value, multiple returns like (result, error), named returns, variadic parameters with ..., anonymous functions and closures.

func uygula(s []int, f func(int) int) []int {
    sonuc := make([]int, len(s))
    for i, v := range s {
        sonuc[i] = f(v)
    }
    return sonuc
}

Functions that take functions (higher-order) gather repeated loops in one place.

defer

defer postpones a call until the function ends; several defers run in reverse order (last in, first out). It's used for cleanup such as closing files and unlocking:

func islem() {
    defer fmt.Println("bitti")
    fmt.Println("çalışıyor")
}
// çalışıyor
// bitti

A defer's arguments are evaluated when the defer line runs; the call itself happens at the end.

Practice Higher-order function

Write the uygula function above. Print the result of uygula([]int{1, 2, 3}, func(n int) int { return n * n }).

Starter code

main.go
package main

import "fmt"

func main() {
    // buraya yaz
}

Sample solution

main.go
package main

import "fmt"

func uygula(s []int, f func(int) int) []int {
    sonuc := make([]int, len(s))
    for i, v := range s {
        sonuc[i] = f(v)
    }
    return sonuc
}

func main() {
    fmt.Println(uygula([]int{1, 2, 3}, func(n int) int { return n * n }))
}

Expected output

[1 4 9]

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What does <code>uygula([]int{1, 2}, func(n int) int { return n + 10 })</code> return?

  • [11 12] Correct answer
  • [1 2]
  • 23
  • [10 10]

Explanation: uygula applies the given function to every element: 1+10, 2+10.

2 Postpone

Question
func oku() {
    ____ fmt.Println("dosya kapandı")
    fmt.Println("okunuyor")
}
Answer
func oku() {
    defer fmt.Println("dosya kapandı")
    fmt.Println("okunuyor")
}

Explanation: defer postpones the call to the end of the function.

3 Group summary

Term Meaning
func ... Definition
(int, error) Multiple returns
...int Variadic
defer Postponing to the end

All lessons in Beginner