Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Go Go Language Overview Data Structures Looping Over Slices

Ronnie Hess
Ronnie Hess
18,124 Points

Looping over slices: I answered the question and got credit... but I think I did it wrong?

When I answered this question (which said in the prompt not to worry about the index), I set up a pretty normal for loop.

I couldn't figure out how to set up a proper for loop without the i for index, but... then I would get an error for not doing anything with the declared i variable!

I just said that i was i to get around it. It worked for the purposes of getting credit but does not seem like best practice.

I commented that trick out in the attached code. How should I make this more appropriate? Get rid of the i variable entirely?

src/utility/print.go
package utility

import "fmt"

func PrintEach(slice []string) {
  for i, v := range slice {
    fmt.Println(v)
    // i = i
    //When I do that, it works, but... FEELS wrong? What's RIGHT?
  }
}

1 Answer

Steven Parker
Steven Parker
221,292 Points

The conventional placeholder for an ignored value is a single underscore:

  for _, v := range slice {