dongxiong5546 2017-02-10 04:02
浏览 45
已采纳

如何确定slice接口的元素类型{}?

I have the following code to double the slice.

func doubleSlice(s []int) []int  {
  t := make([]int, len(s), (cap(s) + 1) * 2 )
  for i := range s {
    t[i] = s[i]
  }
  return t
}

I want to make the func to double any type of slice. And I need to know the element type first.

func showInterfaceItem(s interface{}) interface{} {
  if reflect.TypeOf(s).Kind() != reflect.Slice {
    fmt.Println("The interface is not a slice.")
    return
  }

  var t interface{}
  newLen := reflect.ValueOf(s).Len()
  newCap := (cap(reflect.ValueOf(s).Cap()) + 1) * 2
  t = make([]reflect.TypeOf(s), newLen, newCap)

  return t
}

The reflect.TypeOf(s) return the type of interface{}, not the type of element. How can I get the element type of slice interface?

  • 写回答

1条回答 默认 最新

  • douan7529 2017-02-10 04:51
    关注

    You can use reflect.TypeOf(s).Elem() to get the type of element of slice.

    package main
    
    import (
        "fmt"
        "reflect"
    )
    
    func doubleSlice(s interface{}) interface{} {
        if reflect.TypeOf(s).Kind() != reflect.Slice {
            fmt.Println("The interface is not a slice.")
            return nil
        }
    
        v := reflect.ValueOf(s)
        newLen := v.Len()
        newCap := (v.Cap() + 1) * 2
        typ := reflect.TypeOf(s).Elem()
    
        t := reflect.MakeSlice(reflect.SliceOf(typ), newLen, newCap)
        reflect.Copy(t, v)
        return t.Interface()
    }
    
    func main() {
        xs := doubleSlice([]string{"foo", "bar"}).([]string)
        fmt.Println("data =", xs, "len =", len(xs), "cap =", cap(xs))
    
        ys := doubleSlice([]int{3, 1, 4}).([]int)
        fmt.Println("data =", ys, "len =", len(ys), "cap =", cap(ys))
    }
    

    The output will be:

    data = [foo bar] len = 2 cap = 6
    data = [3 1 4] len = 3 cap = 8
    

    Check it in: Go Playground

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效