Sobes.tech
Junior

What is an empty interface in Go?

sobes.tech AI

Answer from AI

The empty interface (interface{}) in Go is an interface that contains no methods. Since any type implicitly implements an interface with no methods, any value of any type can be assigned to a variable of the empty interface type.

This is useful for the following purposes:

  • Storing values of any type: The empty interface can be used to create collections (slices, maps) or struct fields that can hold values of different types. This is similar to using "any" or "object" in other languages, but with explicit type control when retrieving values.

    // Example 1: Slice storing different data types
    var data []interface{}
    data = append(data, 1)         // int
    data = append(data, "hello")   // string
    data = append(data, true)      // bool
    
  • Working with unknown data types: Functions that need to accept values of any type can use the empty interface as a parameter.

    // Example 2: Function that can print a value of any type
    func printAnything(v interface{}) {
    	fmt.Println(v)
    }
    

When working with values of type interface{}, type assertion or type switch is often used to determine the actual type of the value and access its specific methods or fields.

  • Type assertion: value.(Type)

    // Example 3: Type assertion
    var i interface{} = 100
    j, ok := i.(int) // j = 100, ok = true
    if !ok {
    	// handle error or incorrect type
    }
    
  • Type switch: switch v := value.(type)

    // Example 4: Type switch
    var x interface{} = "world"
    switch v := x.(type) {
    case int:
    	fmt.Println("integer:", v)
    case string:
    	fmt.Println("string:", v)
    default:
    	fmt.Println("unknown type")
    }
    

It is important to remember that using the empty interface loses the advantages of static typing in Go. Type safety is only guaranteed through explicit assertion or switching. Excessive use can make the code less readable and prone to runtime errors.