[英]In Go, how can I partition a slice/array/string of any type?
Guava has a generic partition method which can not directly be implemented in Go due to Go's lack of generics. Guava具有通用分区方法 ,由于Go缺乏通用属性,因此无法直接在Go中实现。 Is there a workaround for this?
有没有解决方法?
I found this question and answer because I needed the same solution, before I created something that already exists. 我找到了这个问题和答案,因为在创建已经存在的东西之前,我需要相同的解决方案。
I did, however, not like the performance of the solution, so I created a package with a faster and more flexible implementation. 但是,我确实不喜欢该解决方案的性能,因此我创建了一个具有更快,更灵活的实现的程序包。
To improve the speed, instead of using channels I used a function that is passed to the function as a callback for the results. 为了提高速度,我没有使用通道,而是使用了一个函数,该函数作为结果的回调传递给该函数。 I also added implementations using slices and an interface, as well as a channel one to compare the performance of all those methods and give users the flexibility to use the method they require.
我还添加了使用切片和接口的实现,以及一个通道,以比较所有这些方法的性能,并为用户提供了使用所需方法的灵活性。
To prevent others also need to create their own implementation I made it publicly available at the following url: https://github.com/crosscode-nl/partition 为了防止其他人也需要创建自己的实现,我在以下URL上公开了它: https : //github.com/crosscode-nl/partition
According a benchmark of the code shows that the channel based solution is slower than the func version. 根据代码的基准测试显示,基于通道的解决方案比func版本慢。
BenchmarkToChan100-4 50000 25862 ns/op
BenchmarkToChan10-4 300000 4939 ns/op
BenchmarkToChan0-4 500000 2727 ns/op
BenchmarkToFunc100-4 5000000 230 ns/op
BenchmarkToFunc10-4 30000000 46.5 ns/op
BenchmarkToFunc0-4 100000000 14.6 ns/op
Example usage: 用法示例:
a := []int{1, 2, 3, 4, 5, 6, 7, 8, 9}
partition.ToFunc(len(a), 5, func(l int, h int) {
fmt.Printf("Part: %v\n", a[l:h])
})
// Output:
// Part: [1 2 3 4 5]
// Part: [6 7 8 9]
See benchmarks in repo for details. 有关详细信息,请参见回购中的基准。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.