0
0
Goprogramming~5 mins

Empty interface in Go

Choose your learning style9 modes available
Introduction
An empty interface can hold any value because it has no methods. It helps when you want to store or pass around any type of data without knowing its exact type.
When you want to write a function that accepts any type of input.
When you need to store different types of values in the same container.
When working with data where the type is not known in advance.
When you want to create flexible APIs that handle multiple data types.
Syntax
Go
var x interface{}
The empty interface is written as interface{} with no methods inside the braces.
It can hold values of any type, like numbers, strings, structs, or even other interfaces.
Examples
Here, 'a' is an empty interface holding an integer value 10.
Go
var a interface{}
a = 10
fmt.Println(a)
The empty interface 'b' holds a string value "hello".
Go
var b interface{} = "hello"
fmt.Println(b)
The empty interface 'c' holds a float value 3.14.
Go
var c interface{}
c = 3.14
fmt.Println(c)
Sample Program
This program shows how an empty interface variable 'x' can hold different types of values. The function 'printValue' accepts any type because it uses an empty interface parameter.
Go
package main

import "fmt"

func printValue(v interface{}) {
    fmt.Printf("Value: %v, Type: %T\n", v, v)
}

func main() {
    var x interface{}

    x = 42
    printValue(x)

    x = "Go language"
    printValue(x)

    x = true
    printValue(x)
}
OutputSuccess
Important Notes
You can use type assertions or type switches to find out the actual type stored in an empty interface.
Using empty interfaces too much can make your code less clear because you lose type safety.
Empty interfaces are very useful when working with generic data or JSON decoding.
Summary
An empty interface can hold any type of value.
It is written as interface{} with no methods.
Use it to write flexible code that works with any data type.