Should I not write two slices in one line?

Hi, I sometimes have written two slices in one line and get an out of bounds runtime error, then I start guessing of course, because both slices could be the reason. Then I rewrite the part so that each slice is having its own line and reproduce the panic again.

Am I correct that stack traces contain no column or is it just me under Windows or so? Will future Go versions have column numbers in stack traces?

Or am I just violating the style guide?

Thanks a lot

1 Like

Do you mean like this?

func main() {
	var a, b []string
	fmt.Println(a, b)

	a[2], b[2] = "a", "b" // Line number here is 11

   panic: runtime error: index out of range [2] with length 0

   goroutine 1 [running]:
   /tmp/sandbox886078500/prog.go:11 +0xcb

It only shows that the panic happened on line 11, you can’t tell if it was the write to a or b that caused the panic.

I think you are correct that stack traces do not contain a column number, but maybe there is some custom recovery implementation that could get you this, but by default it doesn’t look like there is.

I think you’d be better off doing these writes on separate lines, so you can see which one panicked, or doing some checking before the write to ensure that the writes will not panic.

1 Like


Some programming languages like Python follow the “It’s easier to ask forgiveness than it is to get permission” idea where you write your code and catch exceptions to handle them. Go favors explicit error handling. Instead of attempting to index into a slice and hoping it has sufficient size, you should check the size first and return an error if it’s not the expected/required size.


Thanks, I think I’ll then face reality, which is, two lines are better than one, currently.

It has actually been a compare of two characters from []rune types,

a[3] == b[4]

and the line break didn’t look nice.

The checking at the top is what I also use, but sometimes I’m prototyping, don’t know what parts to collect to the top part that sanity checks input. I want it to be documenting itself and really be good, but I’m kind of sure I’ll forget to pre-check a few slice things now and then.

And reproducing panics makes me a very little bit frustrated, so …

I really needed to ask this, thanks a lot. :slight_smile:

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.