LoginSignup
6
3

More than 5 years have passed since last update.

Go言語でPHPのarray_chunkのようなことをする

Posted at

例えば、

[]string{"a", "b", "c", "d", "e", "f", "g", "h"}

のような1次元のスライスを

[][]string{
    []string{"a", "b", "c"}, 
    []string{"d", "e", "f"},
    []string{"g", "h"},
}

のように3個ずつのスライスに分割した2次元スライスにしたい。

実装してみた

main.go
package main

import (
    "log"
)

func main() {
    slice := []string{"a", "b", "c", "d", "e", "f", "g", "h"}
    chunkedSlice := chunkStringSlice(slice, 3)
    log.Printf("%#v", chunkedSlice)
}

func chunkStringSlice(slice []string, size int) [][]string {
    var chunks [][]string

    sliceSize :=  len(slice)

    for i := 0; i < sliceSize; i += size {
        end := i+size
        if sliceSize < end {
            end = sliceSize
        }
        chunks = append(chunks, slice[i:end])
    }

    return chunks
}

実行結果

2013/12/12 17:20:23 [][]string{[]string{"a", "b", "c"}, []string{"d", "e", "f"}, []string{"g", "h"}}

課題

文字列型のスライスにのみ使える関数になってしまった。スライスに対する操作しかないので、もう少し汎用度高めたい。

6
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
3