How to declare a multidimensional array of two different data types

I'm a newbie, I have a Tuple list in python, as you see below:

data = [ (435347,'cat'), (435347,'feline'), (435347,'lion'), (6765756,'dog'), (6765756,'hound'), (6765756,'puppy'), (435347,'kitten'), (987977,'frog') ] 

how can I convert the data to the GO equivalent, I googled, but everywhere they pointed with the same type of data array type like this,

 int_list := [4][2]int{{1, 0}, {2, 0}, {3, 0}, {4, 0}} string_list := make([][]string, 0) a := [1][2]string{{"lion","dog"}} 

help me!..

Updated:

for arrays of mixed type:

 array := []interface{}{1, "dog", "lion", 12, 45.09, true, false} 
+5
source share
2 answers

There are two possible solutions here: real multidimensional arrays of mixed data types (which you seem to be asking for) and arrays of structures (which you probably want).

Multidimensional Arrays of Mixed Data Types Using Interfaces

If you really want to use multidimensional arrays of mixed types, you need to use interfaces:

 interfaceArray := [2][2]interface{}{{1,"dog"},{2,"cat"}} fmt.Println(interfaceArray) 

Outputs:

[[1 dog] [2 cat]]

Interfaces should be handled with care, as they can be ... anything. This means that there is no compulsion for the first argument to be int and the second to be a string. I can also easily add {"lion", 3} , and the compiler will be happy, but your program will fail if it does not check the type first.

You can make conversions and assertions on interfaces to provide the right data types.

Array of structured data

Putting python tuples into a list does not make it multidimensional. Go's closest equivalent is an array of structures.

 type animal struct { id int name string } animalList := [2]animal{{1, "cat"}, {2, "dog"}} fmt.Println(animalList) 

Outputs:

[{1 cat} {2 dog}]

In this case, the types are clearly defined, and I cannot save {"lion", 3} in an array.

final note : [size]type defines an array. []type defines a slice. I use arrays here, as this is what you mention in your question, but the fragments will be the same (or probably more) appropriate.

+4
source

You cannot create a multidimensional array with two different types. Better to use structure. Hope this works for your purpose.

 package main import "fmt" type Data struct { i int s string } func main() { data := []Data{ {435347,"cat"}, {435347,"feline"}, {435347,"lion"}, } fmt.Println(data) } 
+6
source

Source: https://habr.com/ru/post/1274972/


All Articles