Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Build array with different types

Tags:

go

I'm very new in Go, and I came from Ruby. So...

can I build array what includes different types

[1, 2, "apple", true]

Sorry if it's stupid question.

Thanks.

like image 441
Oleh Sobchuk Avatar asked Sep 07 '16 18:09

Oleh Sobchuk


People also ask

Can you have an array with different data types?

You can create an array with elements of different data types when declare the array as Object. Since System. Object is the base class of all other types, an item in an array of Objects can have a reference to any other type of object.

How do you create an array of different objects?

An Array of Objects is created using the Object class, and we know Object class is the root class of all Classes. We use the Class_Name followed by a square bracket [] then object reference name to create an Array of Objects.

How do you create an array with different data types in Java?

Creating an Object[] array is one way to do it. Otherwise, you can create a class with the variables you want, and have an array of that class's objects. class MyClass{ int var_1; String var_2; ... ... } ... MyClass[] arr = new MyClass[3];

Can a 2d array have different data types?

You can have multiple datatypes; String, double, int, and other object types within a single element of the arrray, ie objArray[0] can contain as many different data types as you need. Using a 2-D array has absolutely no affect on the output, but how the data is allocated.


1 Answers

You can do this by making a slice of interface{} type. For example:

func main() {
    arr := []interface{}{1, 2, "apple", true}
    fmt.Println(arr)

    // however, now you need to use type assertion access elements
    i := arr[0].(int)
    fmt.Printf("i: %d, i type: %T\n", i, i)

    s := arr[2].(string)
    fmt.Printf("b: %s, i type: %T\n", s, s)
}

Read more about this here.

like image 152
abhink Avatar answered Oct 06 '22 01:10

abhink