如何构建混合数组

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

How to build mixed array

问题

在Go语言中,可以使用空接口类型(interface{})来实现包含不同类型的数组。空接口类型可以接受任何类型的值作为其元素。

以下是在Go中声明和填充包含不同类型的数组的示例:

package main

import "fmt"

func main() {
    arr := []interface{}{1, "hello", true}
    fmt.Println(arr)
}

在上面的示例中,我们声明了一个空接口类型的切片([]interface{}),并将不同类型的值(整数、字符串和布尔值)填充到该切片中。通过使用空接口类型,我们可以在同一个数组中存储不同类型的值。

希望这可以帮助到你!如果你有任何其他问题,请随时问我。

英文:

In ruby I can created array is filled with types:

[1, 'hello', :world] # [Fixnum, String, Symbol]
=> [1, "hello", :here]

How to implement a similar array is filled with mixed types in Go?

How to declare the array?

答案1

得分: 12

你可以通过空接口interface{}来实现:

arr := make([]interface{}, 0)

arr = append(arr, "asdfs")
arr = append(arr, 5)

或者使用字面形式:

arr := []interface{}{"asdfs", 5}

当你想要使用该数组的值时,你需要使用类型断言。

英文:

You can do that via the empty interface - interface{}:

arr := make([]interface{}, 0)

arr = append(arr, "asdfs")
arr = append(arr, 5)

or in literal form:

arr := []interface{}{"asdfs", 5}

Whenever you want to use a value of that array you need to use a type assertion.

huangapple
  • 本文由 发表于 2015年3月21日 21:46:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/29183434.html
匿名

发表评论

匿名网友

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

确定