w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Is working past the end of a slice idiomatic?

This is not abusing the slice, this is just perfectly using what a slice is : a window over an array.

I'll take this illustration from another related answer I made :

 array : [0 0 0 0 0 0 0 0 0 0 0 0]
 array :  <----   capacity   --->
 slice :     [0 0 0 0]
 slice :      <---- capacity ---> 

When the array is greater than the slice it's normal and standard to take a greater slice by extending one when you know you don't go out of the underlying array (which can be verified using cap()).

Regarding your buggy code you give as example, yes, it might be dangerous, but arrays and slices are among the most basic structures of the languages and you must understand them before you use them if you want to avoid such bugs. I personally think that any go coder should not only know the API but also what are slices.

In the code you link to, a short analysis shows that there is no possible overflow possible as list is created as

list := make([]literalNode, len(freq)+1)

and is later resized to count which can't be greater than len(freq) :

list = list[0:count]

One might have preferred a few more comments but as the function containing list = list[0 : n+1] is private and called from only one place, it might also be considered the balancing between comment verbosity and code obscurity sounds right. It's painful to have too much comments hiding the code and anybody in need to read this code is able to easily check there is no overflow just like I did.

© Copyright 2018 w3hello.com Publishing Limited. All rights reserved.