簡體   English   中英

如何迭代Go中的數組,從索引中間開始,然后從索引0繼續?

[英]How to iterate an array in Go, starting from the index middle and then continue from index 0?

我的目標是從中間迭代一個數組,然后從索引 0 繼續。

完整代碼

當前的解決方案是復制 body 塊

    for _, daysInMonth := range daysInMonths[a.Month()-1:] {
        daysDiff -= float64(daysInMonth)
        if daysDiff < 0 {
            daysDiff += float64(daysInMonth)
            break
        }

        monthsDiff += 1
    }
    for _, daysInMonth := range daysInMonths {
        daysDiff -= float64(daysInMonth)
        if daysDiff < 0 {
            daysDiff += float64(daysInMonth)
            break
        }

        monthsDiff += 1
    }

如果您在月份達到 12 時將 monthDiff 設置回零,它應該可以工作。

monthsDiff = 0
// i.e. a.Month() is 10
// then subtract daysDiff with days of Month 10, 11, 12, 1, 2, and so on.
for _, daysInMonth := range daysInMonths[a.Month()-1:] {
    daysDiff -= float64(daysInMonth)
    if daysDiff < 0 {
        daysDiff += float64(daysInMonth)
        break
    }

    if monthDiff == 12 {
        monthsDiff = 0
    } else {
        monthsDiff += 1
    }

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM