如何在Go语言中限制结构体循环的次数?

huangapple go评论74阅读模式
英文:

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

问题

我正在尝试让一个Struct在循环十次后停止。我的Struct看起来像这样:

type Book struct {
    Id string
    Title string
}

而遍历整个结构的代码是:

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

我尝试使用一个单独的循环,循环十次,但这只是循环了整个Struct十次,或者只循环了Struct的一部分十次。

英文:

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

得分: 1

根据Jim在评论部分提到的,你正在循环遍历之前在代码行中声明的所有书籍,而这个书籍列表实际上是一个空的切片(所以你根本不会进行循环)。

然而,在使用for循环遍历范围时,第一个参数是当前元素的索引。有了这个索引,你可以在循环中设置一个条件,以便在超出任意限制时退出循环。

// books是一个Book切片 -> []Book
for i, book := range books {
// 如果你在切片的第11个元素上
if i == 10 {
// 退出循环
break
}
// 对book进行任何你想做的操作
}

英文:

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
}

huangapple
  • 本文由 发表于 2021年12月20日 23:37:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/70424253.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定