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.
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.
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.
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];
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With