CodeBlanks Logo Icon CodeBlanks

Summary - Interface and error

Combine interface and error to write a validator.

Interfaces and errors summary

An interface = a list of methods; types satisfy it implicitly. Small interfaces (io.Reader, fmt.Stringer) are powerful abstractions. error is an interface too: Error() string. Errors are created with errors.New and fmt.Errorf("...: %w", err), returned as the last value, and inspected with errors.Is (value) and errors.As (type).

Type switch

To branch on the real type of an interface value, use switch v := x.(type):

func tanimla(x any) string {
    switch v := x.(type) {
    case int:
        return fmt.Sprintf("tam sayı %d", v)
    case string:
        return "metin " + v
    case error:
        return "hata: " + v.Error()
    default:
        return "bilinmeyen"
    }
}

Practice Describe it

Write the tanimla(x any) string function above with a type switch. Print the results for 42, "go", errors.New("x") and 3.5 on separate lines.

Starter code

main.go
package main

import (
    "errors"
    "fmt"
)

func main() {
    // buraya yaz
}

Sample solution

main.go
package main

import (
    "errors"
    "fmt"
)

func tanimla(x any) string {
    switch v := x.(type) {
    case int:
        return fmt.Sprintf("tam sayı %d", v)
    case string:
        return "metin " + v
    case error:
        return "hata: " + v.Error()
    default:
        return "bilinmeyen"
    }
}

func main() {
    for _, x := range []any{42, "go", errors.New("x"), 3.5} {
        fmt.Println(tanimla(x))
    }
}

Expected output

tam sayı 42
metin go
hata: x
bilinmeyen

Questions and answers

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

1 What can the empty interface <code>any</code> (<code>interface{}</code>) hold?

  • Only structs
  • Only nil
  • Only numbers
  • A value of any type Correct answer

Explanation: Every type satisfies an interface with no methods; using the value requires a type assertion or a type switch.

2 Type switch

Question
switch v := x.(____) {
case int:
    fmt.Println("int", v)
}
Answer
switch v := x.(type) {
case int:
    fmt.Println("int", v)
}

Explanation: x.(type) is used only inside a switch and branches on the real type.

3 Group summary

Term Meaning
interface Behavior contract
any Any type
x.(type) Branching by type
errors.Is / As Error chain

All lessons in Beginner