Can I build array what includes different types? For example:
[1, 2, "apple", true]
Can I build array what includes different types? For example:
[1, 2, "apple", true]
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.
Depending on the situation, you might be able to use a struct instead:
package main
import "fmt"
type array struct {
one, two int
fruit string
truth bool
}
func main() {
arr := array{1, 2, "apple", true}
fmt.Println(arr)
}