The usual slice syntax in Golang is a[low:high], which you are probably familiar with. There is also another slice syntax in the form of a[low:high:ma

a[low:high:max] in Golang — A Rare Slice Trick

submited by
Style Pass
2023-03-18 17:00:04

The usual slice syntax in Golang is a[low:high], which you are probably familiar with. There is also another slice syntax in the form of a[low:high:max], which takes three indexes instead of two. What does the 3rd index max do? Hint: It is not the step index in the Python slice syntax a[low:high:step].

Answer: The 3rd index is for setting the capacity of the slice! It is called a “full slice expression” in the Golang specification.

Out-of-bounds errors are common in C programs, and Golang mitigates this problem by having built-in runtime bounds checkers. Bounds checking for arrays is simple because Golang arrays are of fixed length, however, bounds checking for pointers is not so simple, because the bounds of pointers are not explicitly defined. Slices in Golang are just one solution to bounds checking for pointers.

Instead of using plain pointers to access array elements, Golang augments pointers with a length field; the result (pointer-with-length) is then called a “slice”, or “fat pointer” elsewhere. With the length field, runtime bounds checking is easy.

Leave a Comment
Related Posts