Sobes.tech
Junior — Middle

How can you determine the specific type of an object implementing an interface?

sobes.tech AI

Answer from AI

In Go, to determine the specific type of an object that implements an interface, type assertion or type switch is used.

Example with type assertion:

var i interface{} = someInterfaceValue
if v, ok := i.(ConcreteType); ok {
    // v has type ConcreteType
    fmt.Println("This is ConcreteType", v)
} else {
    fmt.Println("Other type")
}

Example with type switch:

switch v := i.(type) {
case ConcreteType:
    fmt.Println("This is ConcreteType", v)
case AnotherType:
    fmt.Println("This is AnotherType", v)
default:
    fmt.Println("Unknown type")
}
How can you determine the specific type of an object… - sobes.tech