Skip to content

Instantly share code, notes, and snippets.

@mustafaturan
Created February 5, 2019 07:00
Show Gist options
  • Star 27 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save mustafaturan/7a29e8251a7369645fb6c2965f8c2daf to your computer and use it in GitHub Desktop.
Save mustafaturan/7a29e8251a7369645fb6c2965f8c2daf to your computer and use it in GitHub Desktop.
Go / Chunk Slice
# https://play.golang.org/p/JxqibtHkuO-
func chunkBy(items []string, chunkSize int) (chunks [][]string) {
for chunkSize < len(items) {
items, chunks = items[chunkSize:], append(chunks, items[0:chunkSize:chunkSize])
}
return append(chunks, items)
}
@117
Copy link

117 commented May 3, 2020

thank you

@lj3lj3
Copy link

lj3lj3 commented Feb 4, 2021

Thank you

@luqman-v1
Copy link

thanks

@jamelt
Copy link

jamelt commented Aug 13, 2021

Nice!

@kamnev8823
Copy link

kamnev8823 commented Feb 14, 2022

You can allocate memory use make() like

var chunks = make([][]string, 0, len(items) / chunkSize + 1)
// or 
// if use this variant, need to be add index into cycle and access via index
var chunks = make([][]string, len(items) / chunkSize + 1)

And you can do like that
this

items[0:chunkSize:chunkSize] 

to

items[:chunkSize:chunkSize]

@alfonmga
Copy link

alfonmga commented May 27, 2022

Nice! Thanks to your code + @kamnev8823 suggestion, here's my final code I shared on StackOverflow (it includes generics support): https://stackoverflow.com/a/72408490/3971297

@SKTT1Ryze
Copy link

thank you

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment