重现一个相同类型的数组

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

Reproducing an array of same type

问题

我想编写一个程序,接收一个数组(包含字符串、整数或其他类型的数组),并创建一个相同类型的新数组,只包含第一个元素。

例如:

对于一个字符串数组 arr := []string("hello", "world")

我的输出将是 arr2 := []string(arr[0]);

我不能使用copy函数,因为这样做的话,我将不得不为其创建(make)一个新的切片。而且在这种情况下,我仍然需要确定第一个数组的类型(字符串、整数、布尔等等)。

也许我可以使用reflect.TypeOf(),但我仍然不知道如何利用这些信息来创建相同类型的切片或数组。

我不考虑使用条件语句来实现。例如:

if reflect.TypeOf(arr) == []int {
   arr := []int(arr[0])
} else if reflect.TypeOf(arr) == []string
   arr := []string(arr[0])
} ...

我很高兴能得到帮助。提前谢谢。

英文:

I would like to write a program that receive a array (of string, int, or whatever) and create another array of the same type contain only the first element.

For example:

for a array of strings arr := []string("hello", "world")

my output would be arr2 := []string(arr[0]);

I can't use the copy function because to do that, i would have to create(make) a new slice for it. And in this case, i still have to discover which type the first array is (string, int, bool, and so on...)

Maybe I could use the reflect.TypeOf() but i would still not know how to use that information to create the same type of slice or array.

i'm not considering to use conditionals for that.
For example:

if reflect.TypeOf(arr) == []int {
   arr := []int(arr[0])
} else if reflect.TypeOf(arr) == []string
   arr := []string(arr[0])
} ...

I would be glad get a help on there.
Thanks in advance.

答案1

得分: 1

你可以直接在原地对其进行切片:

s2 := s1[0:1]

但如果你真的需要创建一个新的切片,可以这样做:

func f(s interface{}) interface{} {
    v := reflect.ValueOf(s)
    t := v.Type()
    res := reflect.MakeSlice(t, 1, 1)
    res.Index(0).Set(v.Index(0))
    return res.Interface()
}

Playground: http://play.golang.org/p/w1N3pgvAwr.

英文:

You could just subslice it in place:

s2 := s1[0:1]

But if you really need to create a new slice, you can do it like this:

func f(s interface{}) interface{} {
    v := reflect.ValueOf(s)
    t := v.Type()
    res := reflect.MakeSlice(t, 1, 1)
    res.Index(0).Set(v.Index(0))
    return res.Interface()
}

Playground: http://play.golang.org/p/w1N3pgvAwr.

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

发表评论

匿名网友

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

确定