SSJX.CO.UK
Browser Games | Cybiko | Amiga | Applications | Windows Games | Java Area | Test Area | Guides | Site Map

Out Of Bounds - Go

Introduction

This is part of a series testing each of the languages I use to see how good they are at catching simple array out of bounds errors.

These tests check for the following:

The Code

The following was compiled using Go version 1.13.5 :

package main

import "fmt"

func main() {
	array := [...]int{1, 2, 3}

	// #1. Simple so should be an easy catch - CT: CAUGHT
	array[3] = 97

	// #2. This is a constant so should also be an easy catch - CT: CAUGHT
	const pa = 3
	array[pa] = 98

	// #3. Variable index but does start outside - CT: FAILED
	pb := 4
	array[pb] = 99

	// #4. Looping through array - CT: FAILED
	for i := 0; i < 4; i++ {
		fmt.Println(array[i])
	}
}

Test 1 - Default Settings

By default checks are on so this is the only test. The compiler picked up errors #1 and #2.

With #1 and #2 commented out, running the above gives 'index out of range' errors.

Extra

To avoid error #4 we can use a range based loop:

	// #4. Looping through array - Better version
	for _, v := range array {
		fmt.Println(v)
	}

Summary

Pretty good result and as expected really so not very interesting to summarise! One of Go's aims is to build reliable software so I guess this helps!

11/01/20