How can I skip the index out of range error?

Hi,all
How can I get the error of index out of range?
I have an unsymetric 2d slice,and I want to get all the columns of it.Since it is unsymetric,when I double loop through it in the normal way,it will panic and stop,it will take a hell lot of effort to control the loop to fix this,Is there anyway to get this index out of range error, and when this error happens,just skip to the next loop, thanks in advance?

Hey @feng12, what exactly are you trying to achieve and what code are you currently trying to use?

Is this the type of thing that you are trying to do, since this is what I am understanding from your question?

package main

import "fmt"

func main() {
	multiDimensionalSlice := [][]string{
		{"a", "b", "c"},
		{"d", "e", "f"},
		{"g", "h", "i"},
	}

	for pos, slice := range multiDimensionalSlice {
		fmt.Printf("position %d: ", pos)
		for key, val := range slice {
			fmt.Printf("[%d: %q]", key, val)
		}
		fmt.Println()
	}
}

Edit: If you are iterating over a slice or an array, just do bounds checking like so:

package main

import "fmt"

func main() {
	slice := []int{1, 3, 5, 7, 9}
	for i := 0; i < 10; i++ {
		if i == len(slice) {
			break
		}
		fmt.Println(slice[i])
	}
}

thanks,radovsky.
I misunderstood the error I got,it has nothing to do with the slice.it actually lies in the string:)
the slice I have is like
[]string{
“abc”,
“def”,
“gh”,
}
I didn’t split it to make it quicker.that’s why I get an out of range error.I just made a very stupid mistake. and I have fixed it now.

1 Like

I am still wondering if there is a better way to do this.for example.
I want to get all the columns of the matrix a:
a := [][]string{
{“a”, “b”, “c”, “d”},
{“e”, “f”, “g”, “h”},
{“i”, “j”},
}

Here is my code:
https://play.golang.org/p/Z3owzthPnZ
I think it is very clumsy.If I can skip the index out of range error,it can save a lot of time

I’m not sure exactly what you mean, but this iterates over every value in a 2d slice. This is from my first response to you earlier.

package main

import "fmt"

func main() {
	multiDimensionalSlice := [][]string{
		{"a", "b", "c"},
		{"d", "e", "f"},
		{"g", "h", "i"},
	}

	for pos, slice := range multiDimensionalSlice {
		fmt.Printf("position %d: ", pos)
		for key, val := range slice {
			fmt.Printf("[%d: %q]", key, val)
		}
		fmt.Println()
	}
}

Sorry,English is not my native language.
my code
I am asking whether it can be better.
1.I want to get the columns,not the rows.
2 Maybe I misused the word unsymetric:
here is what I think the difference between symetric and unsymetric
symetric is:
a b c
d e f
g h i

unsymetric is
a b c
d e f
g

In the example, the answer should be adg be cf.

I guess it can be done by just a single double loop.something like this:
assume the matrix is stored in arr

     var res []string
     for i:=0;i<len(arr[0]);i++{
       str:=""
       for j:=0;j<len(arr);j++{   
              if arr[i][j] index out of range err{
                   ignore it
              }else{
                   str+=arr[i][j]
              }          
              res=append(res,str)
       }
    }

but I don’t know how to write the grammer.
In my code,First I fix(fullfil) the unsymetric matrix to symetrc matrix,using space(" "), Then I loop through every columns, taking out every element but " ", it is unnessary if we can just ignore that err, right?
Thanks anyway,radovskyb.

Hey again @feng12, did you want something like this?

package main

import "fmt"

func main() {
	multiDimensionalSlice := [][]string{
		{"a", "b", "c"},
		{"d", "e", "f"},
		{"g", "h"},
		{"i", "j", "k"},
		{"l"},
		{"m", "n", "o", "p"},
	}

	pos := 0
	for range multiDimensionalSlice {
		for _, row := range multiDimensionalSlice {
			if pos < len(row) {
				fmt.Print(row[pos])
			}
		}
		fmt.Println()
		pos++
	}
}

Edit 1: this version doesn’t print the extra white spaces from above.
Edit 2: oh and this version saves the result to a string separated by spaces like you wanted.

Thanks a lot,radovskyb!
I really like this way :slight_smile:

1 Like

Anytime :slight_smile:

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