Golang Interface{} and Type Assertions

In Go (Golang), the interface{} type is an empty interface that can hold values of any type. It is often used when you need to work with values of unknown or varied types. Type assertions allow you to extract and work with the underlying concrete type of a value stored in an interface{}. Here, we’ll explore how to use interface{} and type assertions in Go.

Storing Different Types in an interface{}

You can store values of different types in an interface{}. Here’s an example:

1
2
3
4
5
6
7
var data = map[string]interface{}{
    "nama":    "john wick",
    "grade":   2,
    "height":  156.5,
    "isMale":  true,
    "hobbies": []string{"eating", "sleeping"},
}

In this map, we have values of various types, such as string, int, float64, bool, and a slice of strings, all stored in the interface{} type.

Extracting Values using Type Assertions

You can use type assertions to extract and work with values of known types from an interface{}. Here’s how you can do it for the values in your data map:

1
2
3
4
5
fmt.Println(data["nama"].(string))
fmt.Println(data["grade"].(int))
fmt.Println(data["height"].(float64))
fmt.Println(data["isMale"].(bool))
fmt.Println(data["hobbies"].([]string))

In each line, we use type assertions to specify the expected type and extract the value from the interface{}. If the actual type doesn’t match the asserted type, it will panic at runtime.

Using a Type Switch for Dynamic Type Handling

To handle values of unknown types dynamically, you can use a type switch. Here’s an example of how to use a type switch to print values based on their types:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
for _, val := range data {
    switch val.(type) {
    case string:
        fmt.Println(val.(string))
    case int:
        fmt.Println(val.(int))
    case float64:
        fmt.Println(val.(float64))
    case bool:
        fmt.Println(val.(bool))
    case []string:
        fmt.Println(val.([]string))
    default:
        fmt.Println("Unknown Type")
    }
}

In this loop, the val.(type) expression checks the type of the value stored in val, and based on the type, it performs the appropriate action. If the type is unknown, it falls back to the default case.

Remember that while using type assertions and type switches, it’s important to handle potential type mismatches or panics to ensure your code is robust.

This is how you can work with interface{} and perform type assertions in Go to handle values of various types in a flexible manner.

0%