在Go语言中,数组的工作方式与Ruby或Python中的数组相同吗?

huangapple go评论75阅读模式
英文:

Do Arrays function the same way in Go as they do in Ruby or Python?

问题

在Go语言中,数组是一种固定长度的数据结构,它只能容纳相同类型的元素。因此,Go语言中的数组不能同时容纳整数和字符串,与Python和Ruby不同。如果你需要在Go语言中存储不同类型的元素,可以使用切片(slice)或者结构体(struct)来代替数组。

英文:

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:

?

答案1

得分: 1

因为Go是一种类型化的语言,要在Go中创建一个包含多种类型的切片,你需要指定一个可以满足多种类型的类型。在Go中,可以通过创建一个空接口(interface{})的切片来实现:

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

这样做的原因是空接口是一个没有方法的接口,所以所有类型都可以匹配它。

在Go中,通常不会创建包含不同类型的切片或数组,但如果确实需要这样做,可以使用上述方法。

你可以在以下链接中了解更多关于接口的内容:

英文:

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:

huangapple
  • 本文由 发表于 2015年7月31日 08:08:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/31736088.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定