簡體   English   中英

Golang:得到切片的類型

[英]Golang: get the type of slice

我使用反射包來獲取任意數組的類型,但得到

   prog.go:17: cannot use sample_array1 (type []int) as type []interface {} in function argument [process exited with non-zero status]

如何從數組中獲取類型? 我知道如何從價值中獲取它。

  func GetTypeArray(arr []interface{}) reflect.Type {
      return reflect.TypeOf(arr[0])
  }

http://play.golang.org/p/sNw8aL0a5f

您正在為切片編制索引這一事實是不安全的 - 如果它是空的,您將獲得索引超出范圍的運行時混亂。 無論如何,由於反射包的Elem()方法 ,它是不必要

type Type interface {

    ...

    // Elem returns a type's element type.
    // It panics if the type's Kind is not Array, Chan, Map, Ptr, or Slice.
    Elem() Type

    ...
}

那么,這就是你想要使用的:

func GetTypeArray(arr interface{}) reflect.Type {
      return reflect.TypeOf(arr).Elem()
}

請注意,根據@ tomwilde的更改,參數arr可以是絕對任何類型,因此沒有什么能阻止您在運行時將GetTypeArray()傳遞給非切片值並引起恐慌。

更改:

GetTypeArray(arr []interface{})

至:

GetTypeArray(arr interface{})

順便說一下, []int不是一個數組,而是一個整數切片

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM