Interface{} vs any in Go: Key Differences and Usage
interface{} is the empty interface type in Go that can hold any value. Starting from Go 1.18, any is an alias for interface{}, making them functionally identical but any is preferred for clearer, modern code.Quick Comparison
This table summarizes the key differences and similarities between interface{} and any in Go.
| Aspect | interface{} | any |
|---|---|---|
| Definition | Empty interface type that can hold any value | Alias for interface{} introduced in Go 1.18 |
| Introduced in | Since the first Go versions | Go 1.18 |
| Syntax | interface{} | any |
| Functionality | Can hold any type | Same as interface{} |
| Readability | Less explicit about intent | More readable and modern |
| Use in Generics | Used before generics for any type | Preferred in generics and modern code |
Key Differences
interface{} is the original empty interface type in Go that can hold any value of any type. It has been part of Go since the beginning and is widely used for generic containers or functions that accept any type.
Starting with Go 1.18, the language introduced generics and added any as a built-in alias for interface{}. This means any is exactly the same type as interface{}, but it improves code readability by clearly expressing the intent to accept any type.
While interface{} and any behave identically at runtime, any is preferred in modern Go code, especially when working with generics, because it makes the code easier to understand and maintain.
Code Comparison
Here is how you use interface{} to accept any type and print it:
package main import "fmt" func printValue(value interface{}) { fmt.Println("Value:", value) } func main() { printValue(42) printValue("hello") printValue(3.14) }
any Equivalent
Here is the same example using any instead of interface{}:
package main import "fmt" func printValue(value any) { fmt.Println("Value:", value) } func main() { printValue(42) printValue("hello") printValue(3.14) }
When to Use Which
Choose any when writing new Go code, especially with generics, to make your intent clear and your code more readable. It is the modern, preferred way to represent any type.
Use interface{} if you are maintaining older code or working in environments where Go versions before 1.18 are required.
Both are interchangeable, but any improves clarity and aligns with current Go best practices.
Key Takeaways
any is an alias for interface{} introduced in Go 1.18.any improves code readability.any in new code and generics for clearer intent.interface{} only for legacy compatibility.