Unlocking Go’s Empty Interface: Store Any Type in One Variable
An empty interface in Go, defined as interface{}, can hold values of any type because it has no methods, enabling flexible data structures like slices, maps, and structs, and is commonly used in functions such as fmt.Println, though copying between typed and empty interface slices requires careful handling.
Empty Interface
An empty interface is an interface that defines no methods. Because it has no methods, any Go value satisfies it, allowing any object to be stored in a variable of type interface{}.
Definition
type empty_int interface{}It is often abbreviated directly as interface{}.
Usage Examples
Declaring an empty interface variable: var i interface{} Using an empty interface as a function parameter, e.g., the fmt package’s Println:
func Println(a ...interface{}) (n int, err error)Empty Interface in Data Structures
You can create slices, maps, or structs that hold interface{} values, enabling storage of heterogeneous types.
Example of a slice of empty interfaces:
package main
import "fmt"
func main() {
any := make([]interface{}, 5)
any[0] = 11
any[1] = "hello world"
any[2] = []int{11, 22, 33, 44}
for _, v := range any {
fmt.Println(v)
}
}The output demonstrates that the slice can hold integers, strings, and other slices.
Copying to an Empty Interface Slice
Directly assigning a typed slice to an []interface{} slice causes a compile‑time error because the memory layout differs (each empty interface element occupies two machine words). To copy, iterate and append each element:
var any []interface{}
for _, v := range testSlice {
any = append(any, v)
}This approach ensures each empty interface element references the underlying value correctly.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
MaGe Linux Operations
Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
