How To Limit The Number of Times A Struct is Looped Through in Go?

656 Views Asked by At

I am trying to have a Struct only be looped through ten times before stopping. My Struct looks like

type Book struct {
    Id string
    Title string
}

and the code that will loop through the entire thing is

var books []Book;
for _, book := range books {
    fmt.Println(book.Id + " " + book.Title);
}

I have tried using a separate for loop that will go ten times but that has only looped through the entire Struct ten times or did one part of the Struct ten times.

1

There are 1 best solutions below

0
On

As mentionned by Jim in the comments sections, you are looping over all books declared on line before, which by the way is an empty slice (so you won't loop at all).

Though in a for loop over a range, the first argument is the index of the current element. With, that you can fix a condition in your loop to exit it if you overflow your arbitrary limit

// books is a slice of Book -> []Book
for i, book := range books {
    // If you are on the eleventh element of your slice
    if i == 10 {
        // leave the loop
        break
    }
// Do whatever you want with book
}