简体   繁体   中英

length and capacity in Go slices

Say we have slice of b such

b:= make([]int, 0, 5) // length: 0, cap: 5

and slice of "c" made from slice of "b"

c:= b[:2]  // length: 2 (?), cap: 5

The question if how come we have length of 2 for "c"? I was expecting length of zero as well, like b, since we are making c out of b

Yep, slicing can get you access to the elements beyond the len of the original slice (though not beyond its cap , or who knows what memory you'd be accessing).

This means, for example, that you can implement append -like functionality, returning a "grown" slice with len increased to something closer to the cap . That is, append 's access to the region between len and cap isn't only available to built-in functions; you have it as well. Look at Append: an example in the Go blog entry on slices to see it done (and if interested read the whole post; it helps make slices as a whole make sense).

The spec on slice expressions (and slice types ) and the Slice Tricks page may also be interesting.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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