Skip to content

Instantly share code, notes, and snippets.

@cslarsen
Last active February 27, 2025 19:38
Show Gist options
  • Save cslarsen/5256744 to your computer and use it in GitHub Desktop.
Save cslarsen/5256744 to your computer and use it in GitHub Desktop.
How to create heterogeneous arrays in Go / golang.
/*
* Example of heterogeneous arrayo in golang.
*
* The trick is simply to create an array that accepts elements that conform
* to the naked interface (an interface with no requirements).
*
* Expected output:
*
* $ go run array.go
* [1 2 3.14 hey {10 20}]
*
*/
package main
import "fmt"
type foo struct {
a int
b int
}
func main() {
a := []interface{}{1, 2, 3.14, "hey", foo{10, 20}}
fmt.Println(a)
}
@nathan-osman
Copy link

And with Go 1.18+, you get the much nicer any type instead of interface{}, making this simple example even simpler.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment