Data type like arrays in Python

Has golang a type of data to save different data types? Like arrays in Python where u can save strings and integers in one array.

As long as all types adhere to the same interface, you can use a slice of the interface type.

1 Like

The Go Programming Language Specification

Interface types

all types implement the empty interface

“all types adhere to the same interface” is trivially true for any type.

package main

import "fmt"

func main() {
	var py []interface{}
	py = append(py, 42)
	py = append(py, "forty-two")
	py0, ok := py[0].(int)
	if ok {
	py1, ok := py[1].(string)
	if ok {

[42 forty-two]

Yeah, though interface{} is nothing you could take much value from…

You can not do anything with the empty interface. A []Foo might be easier to deal with, as you do not need to do any type assertions.

Though if you want to have primitivs in the slice, there is sadly no way around interface{} and type assertions.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.