Sobes.tech
Junior — Middle

Kas oleksite võimeline selgitama, mida tähendab tüüp programmeerimises?

sobes.tech AI

Vastus AI-lt

Type assertion in programming, especially in Go, is a way to obtain the value of a specific type from an interface type.

In Go, variables of interface type can contain values of any type, and type assertion allows checking and extracting a specific type from the interface.

Example:

var i interface{} = "hello"

s, ok := i.(string) // s will be "hello", ok — true

if ok {
    fmt.Println(s) // outputs: hello
} else {
    fmt.Println("i does not contain a string")
}

If the type assertion fails and the second parameter ok is not used, a panic occurs. Therefore, the form with two return values is often used for safe checking.