0
0
GoComparisonBeginner · 3 min read

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.

Aspectinterface{}any
DefinitionEmpty interface type that can hold any valueAlias for interface{} introduced in Go 1.18
Introduced inSince the first Go versionsGo 1.18
Syntaxinterface{}any
FunctionalityCan hold any typeSame as interface{}
ReadabilityLess explicit about intentMore readable and modern
Use in GenericsUsed before generics for any typePreferred 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:

go
package main

import "fmt"

func printValue(value interface{}) {
    fmt.Println("Value:", value)
}

func main() {
    printValue(42)
    printValue("hello")
    printValue(3.14)
}
Output
Value: 42 Value: hello Value: 3.14
↔️

any Equivalent

Here is the same example using any instead of interface{}:

go
package main

import "fmt"

func printValue(value any) {
    fmt.Println("Value:", value)
}

func main() {
    printValue(42)
    printValue("hello")
    printValue(3.14)
}
Output
Value: 42 Value: hello Value: 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.
Both types can hold any value, but any improves code readability.
Use any in new code and generics for clearer intent.
Use interface{} only for legacy compatibility.
Functionally, they behave exactly the same at runtime.