简体   繁体   English

如何在子切片中分割 Go 中的切片

[英]How to split a slice in Go in sub-slices

I'm recently using Go to create applications.我最近在使用 Go 创建应用程序。 My question is this: at a certain point in the program I have a string slice:我的问题是:在程序的某个点我有一个字符串切片:

my_slice = []string{"string1","string2","string3","string4","string5","string6"}

It contains 6 strings.它包含 6 个字符串。 Which is the best procedure (easier to write and understand) to break this slice into 3 parts, for example, and distribute the content in three sub-slices?例如,将这个切片分成 3 个部分并将内容分布在三个子切片中的最佳程序是什么(更容易编写和理解)? If I have:如果我有:

var my_sub_slice1 []string
var my_sub_slice2 []string
var my_sub_slice3 []string

I wish at the end of it my_sub_slice1 will contain (in his first two entries) "string1","string2" ;我希望在它的结尾my_sub_slice1将包含(在他的前两个条目中) "string1","string2" my_sub_slice2 will contain (in his first two entries) "string3","string4" ; my_sub_slice2将包含(在他的前两个条目中) "string3","string4" my_sub_slice3 will contain (in his first two entries) "string5","string6" . my_sub_slice3将包含(在他的前两个条目中) "string5","string6" I know the question is easy but I haven't found a clean and efficient way to do this yet.我知道这个问题很简单,但我还没有找到一种干净有效的方法来做到这一点。 Thanks a lot!非常感谢!

A general solution to split a slice to into sub-slices of equal length将切片拆分为等长子切片的通用解决方案

s := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
size := 2
var j int
for i := 0; i < len(s); i += size{
    j += size
    if j > len(s) {
        j = len(s)
    }
    // do what do you want to with the sub-slice, here just printing the sub-slices
    fmt.Println(s[i:j])
}

// output
// [1 2]
// [3 4]
// [5 6]
// [7 8]
// [9 10]
my_sub_slice1 := my_slice[0:2]
my_sub_slice2 := my_slice[2:4]
my_sub_slice3 := my_slice[4:6]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM