Skip to content

Instantly share code, notes, and snippets.

@mustafaturan
Created February 5, 2019 07:00
Show Gist options
  • Select an option

  • Save mustafaturan/7a29e8251a7369645fb6c2965f8c2daf to your computer and use it in GitHub Desktop.

Select an option

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)
}
@luqman-v1

Copy link
Copy Markdown

thanks

@jamelt

jamelt commented Aug 13, 2021

Copy link
Copy Markdown

Nice!

@kamnev8823

kamnev8823 commented Feb 14, 2022

Copy link
Copy Markdown

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]

@exwyezed

exwyezed commented May 27, 2022

Copy link
Copy Markdown

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
Copy Markdown

thank you

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