search

Explain the use of Go's type assertion and type switch for type checking and switching in Go?

The use of Go's type assertion and type switch are as follows:

Type assertion and type switch are two language constructs in Go that allow you to work with values of different types. They are commonly used when dealing with interfaces, where you may not know the underlying type of the value.

Type assertion is a way to extract a value of a specific type from an interface. 

It has the following syntax:

value, ok := interfaceValue.(typeToAssert)

Here, **interfaceValue** is an interface value and **typeToAssert** is the type you want to assert the value to. The **ok** variable is a boolean that indicates whether the assertion succeeded or not. If the assertion succeeded, **value** will contain the value of type **typeToAssert**, otherwise it will be set to the zero value of that type.

For example, consider the following code:

var i interface{} = "hello"
s, ok := i.(string)
if ok {
    fmt.Println(s)
}

Here, we define an empty interface value **i** that contains the string "hello". We then use type assertion to extract the string value from **i** and assign it to the variable **s**. Since the assertion succeeds, we print the value of **s**, which is "hello".

Type switch is another way to work with values of different types in Go. It allows you to check the underlying type of an interface value and take different actions depending on the type. 

It has the following syntax:

switch v := interfaceValue.(type) {
case type1:
    // do something with v of type1
case type2:
    // do something with v of type2
default:
    // handle other types
}

Here, **interfaceValue** is an interface value and **type1** and **type2** are types you want to check against. Inside each case block, the variable **v** will contain the value of the corresponding type. If none of the cases match, the code in the default block will be executed.

For example, consider the following code:

var i interface{} = 42
switch v := i.(type) {
case int:
    fmt.Printf("twice %v is %v\n", v, v*2)
case string:
    fmt.Printf("%q is %v bytes long\n", v, len(v))
default:
    fmt.Printf("I don't know about type %T!\n", v)
}

Here, we define an empty interface value **i** that contains the integer value 42. We then use a type switch to check the type of **i** and perform different actions depending on the type. Since the type of **i** is **int**, the first case block is executed and we print "twice 42 is 84".

Related Questions You Might Be Interested