iterating over 2d slice causes trouble

576 views
Skip to first unread message

petrov...@gmail.com

unread,
Jul 3, 2013, 5:13:10 AM7/3/13
to golan...@googlegroups.com
Hello everyone ! I am new to Go and have been following tutorials and blog posts to learn it .  I am trying to print a 2d array of slices and have run into the following problem

func PrintGrid(grid [][]int ) {
         for x := range grid {
            fmt.Println()
             for i := range x {
                  if x[i] == 0 {
                      fmt.Printf(".")
                 } else {
                    fmt.Printf("^")
                 }
             }
          }  // end for
 } // end PrintGrid

the compiler prints out the following error message
./gameoflife.go:27: cannot range over x (type int)

can you tell me where I went wrong and the right way to loop over such 2d slices ? Thanks


Dave Cheney

unread,
Jul 4, 2013, 10:10:32 PM7/4/13
to petrov...@gmail.com, golang-nuts
http://play.golang.org/p/ZylI0fm3Cr
> --
> You received this message because you are subscribed to the Google Groups
> "golang-nuts" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to golang-nuts...@googlegroups.com.
> For more options, visit https://groups.google.com/groups/opt_out.
>
>

Jesse McNelis

unread,
Jul 4, 2013, 10:14:43 PM7/4/13
to petrov...@gmail.com, golang-nuts
On Wed, Jul 3, 2013 at 7:13 PM, <petrov...@gmail.com> wrote:
Hello everyone ! I am new to Go and have been following tutorials and blog posts to learn it .  I am trying to print a 2d array of slices and have run into the following problem

func PrintGrid(grid [][]int ) {
         for x := range grid {
the compiler prints out the following error message
./gameoflife.go:27: cannot range over x (type int)

can you tell me where I went wrong and the right way to loop over such 2d slices ? Thanks

In a single value context range gives you the index in the slice not the items in the slice.
In the multi-value context range gives you the index and the item.

You probably want:
for _,x:= range grid {}
This ignores the index value and assigns the item to x.

 



--
=====================
http://jessta.id.au

Reply all
Reply to author
Forward
0 new messages