英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论