20

Can I build array what includes different types? For example:

[1, 2, "apple", true]
3
  • 2
    While there are ways to do this in Go, and perhaps there are valid use cases, I would recommend not doing this. It looks like you're trying to translate your Ruby knowledge and experience to Go, and this probably isn't a good idea. Go's typing is different from Ruby's, and requires a different way of thinking and programming. Commented Sep 7, 2016 at 18:22
  • @Carpetsmoker thanks, I see what you mean, but I just wanna to know Go ability Commented Sep 7, 2016 at 18:24
  • If you are new to Go: Maybe it would be helpful to stick to "proper", safe and idiomatic Go and leave the borders of the Go universe unexplored for a few months? Commented Sep 8, 2016 at 7:14

2 Answers 2

25

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.

Sign up to request clarification or add additional context in comments.

3 Comments

"now you need to use type switches access elements" What you have there isn't a "type switch"; it's a type assertion.
@Tim: fixed. Thanks
To be precise it's a slice of same type - interface{}, not an array with different types elements.
3

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)
}

https://golang.org/ref/spec#Struct_types

1 Comment

The question clearly stated array, why use a struct?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.