Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to build mixed array

Tags:

go

In ruby I can created array is filled with types:

[1, 'hello', :world] # [Fixnum, String, Symbol]
=> [1, "hello", :here]

How to implement a similar array is filled with mixed types in Go?

How to declare the array?

like image 300
itsnikolay Avatar asked Mar 21 '15 13:03

itsnikolay


People also ask

How do you create a mixed array?

You can create JavaScript array with mixed data types as well, for example, array containing both numbers and strings: var MixArr = [1, “Mixed”, 2, “Array”]; You may also use new keyword to create array objects: var JSArr = new array (1,2,3,”String”);

What is a mixed array?

From APL Wiki. In nested array theory, a mixed array is one that mixes simple scalar characters and numbers, or simple scalars with arrays which are not simple scalars. Such an array cannot be formed in flat array theory, which does not allow mixing of the character, number, and boxed types.

Can you have a mixed data type array in Java?

Yes we can store different/mixed types in a single array by using following two methods: Method 1: using Object array because all types in . net inherit from object type Ex: object[] array=new object[2];array[0]=102;array[1]="csharp";Method 2: Alternatively we can use ArrayList class present in System.

Can array have different data types in Swift?

It is important to note that, while creating an empty array, we must specify the data type inside the square bracket [] followed by an initializer syntax () . Here, [Int]() specifies that the empty array can only store integer data elements. Note: In Swift, we can create arrays of any data type like Int , String , etc.


1 Answers

You can do that via the empty interface - interface{}:

arr := make([]interface{}, 0)

arr = append(arr, "asdfs")
arr = append(arr, 5)

or in literal form:

arr := []interface{}{"asdfs", 5}

Whenever you want to use a value of that array you need to use a type assertion.

like image 124
Stephan Dollberg Avatar answered Oct 07 '22 00:10

Stephan Dollberg