-1

In Ruby an array can hold a string or an integer, the same seems true in Javascript and python. But in Go, putting integers and strings together seems difficult, or at least i couldn't figure it out. Is an array able to take both integers and strings within Go in the same way that Python and Ruby can?

Ruby:

a = [20, "tim"]
puts a

Python:

a = [20, "tim"]
print(a)

Go:

?
Caleb
  • 9,272
  • 38
  • 30
codedownforwhat
  • 173
  • 2
  • 14
  • 3
    Yeah, they aren't the same; they're typed. You can explicitly make a `[]interface{}` but I honestly don't see that many places (though it's in some important spots like the signature of `fmt.Println` and similar functions I guess). You probably want to check out https://tour.golang.org/ to get started with Go. – twotwotwo Jul 31 '15 at 00:14
  • What do you mean by typed? You mean they type (40) int ("name") string right? I did but i am pretty new to programming so it's definitely confusing. – codedownforwhat Jul 31 '15 at 00:30
  • 1
    Yeah, that kind of type. Do [the tour](https://tour.golang.org/) or find Go or introductory programming materials, though--StackOverflow isn't structured to be a good way to learn programming. – twotwotwo Jul 31 '15 at 00:36
  • They're similar enough that `a = [20, "tim]` is a syntax error in all three languages. – hobbs Jul 31 '15 at 01:17

1 Answers1

1

Because Go is a typed language, to create a slice of multiple types in Go, you need to specify a type that multiple types can satisfy. To do this in Go, create a slice of the empty interface (interface{}) such as the following:

a := []interface{}{20, "tim"}
fmt.Println(a)

This works because the empty interface is an interface with no methods so all types will match it.

Creating a slice or array of mixed types isn't generally done in Go but this is the way to do it if you need it.

You can read more about interfaces here:

Grokify
  • 15,092
  • 6
  • 60
  • 81
  • Thanks. Will checkout interfaces. I see learning Go makes me look much deeper into programming concepts than with Python and it's definitely more difficult at first. – codedownforwhat Jul 31 '15 at 01:30
  • Might also suggest the tour, or some general introduction to static vs. dynamic typing (but I don't know where a good one is). – twotwotwo Jul 31 '15 at 01:37
  • Click on the Go tag, then click on the "info" tab for a great list of Golang resources. – LanceH Jul 31 '15 at 13:11