How to Use interface{} in Go: Simple Guide with Examples
In Go,
interface{} is the empty interface that can hold values of any type because every type implements it. You use it when you want a variable to store any kind of value, but you often need type assertion to get the original value back.Syntax
The interface{} type is the empty interface in Go. It can hold any value because all types implement zero methods, which matches the empty interface.
Use it like this:
var x interface{}declares a variablexthat can hold any value.- You can assign any value to
x, likeint,string, or custom types. - To get the original value back, use type assertion like
value, ok := x.(int).
go
var x interface{} x = 42 x = "hello"
Example
This example shows how to store different types in an interface{} variable and how to get the original value back using type assertion.
go
package main import "fmt" func main() { var data interface{} data = 100 fmt.Println("data holds int:", data) data = "Go language" fmt.Println("data holds string:", data) // Type assertion to get string value str, ok := data.(string) if ok { fmt.Println("Type assertion succeeded, string value:", str) } else { fmt.Println("Type assertion failed") } // Wrong type assertion num, ok := data.(int) if ok { fmt.Println("Type assertion succeeded, int value:", num) } else { fmt.Println("Type assertion failed for int") } }
Output
data holds int: 100
data holds string: Go language
Type assertion succeeded, string value: Go language
Type assertion failed for int
Common Pitfalls
Common mistakes when using interface{} include:
- Assuming the stored value is always a certain type without checking, which causes a panic.
- Not using the "comma ok" idiom in type assertion to safely check the type.
- Overusing
interface{}can make code harder to understand and maintain.
Always check the type assertion result before using the value.
go
package main import "fmt" func main() { var x interface{} = "hello" // Unsafe type assertion - causes panic if wrong // n := x.(int) // This will panic // Safe type assertion n, ok := x.(int) if ok { fmt.Println("Value is int:", n) } else { fmt.Println("Value is not int") } }
Output
Value is not int
Quick Reference
| Concept | Description |
|---|---|
| interface{} | Empty interface that holds any type |
| var x interface{} | Declare variable x of empty interface type |
| x = value | Assign any value to x |
| value, ok := x.(Type) | Type assertion to get original value safely |
| panic on wrong assertion | Avoid by checking ok before use |
Key Takeaways
interface{} can hold any type because all types implement it.
Use type assertion with the "comma ok" idiom to safely get the original value.
Avoid panics by always checking the type assertion result.
Overusing interface{} can reduce code clarity; use it only when needed.
interface{} is useful for functions that handle any type of data.