AdSense

網頁

2021/8/20

Golang for迴圈continue Label範例

使用for迴圈搭配continue Label遍歷slice deps篩選出員工年紀(Employee.Age)都不超過30的Department


範例環境:

  • Go 1.16

main.go

package main

import "fmt"

type Employee struct {
    Id   int
    Name string
    Age  int
}

type Department struct {
    Id        int
    Name      string
    Employees []Employee
}

func main() {
    deps := []Department{
        {
            Id:   1,
            Name: "HR",
            Employees: []Employee{
                {Id: 1, Name: "John", Age: 33},
                {Id: 2, Name: "Mary", Age: 28},
            },
        },
        {
            Id:   2,
            Name: "Mkt.",
            Employees: []Employee{
                {Id: 3, Name: "Bill", Age: 18},
                {Id: 4, Name: "Nick", Age: 17},
            },
        },
    }

    result := filterDeptAllEmpAgeLessThen30(deps)

    fmt.Println(result)
}

func filterDeptAllEmpAgeLessThen30(deps []Department) (result []Department) {
Outer:
    for i := 0; i < len(deps); i++ { // outer loop
        dep := deps[i]
        if dep.Employees != nil && len(dep.Employees) != 0 {
            emps := dep.Employees
            for j := 0; j < len(emps); j++ { // inner loop
                emp := emps[j]
                if emp.Age > 30 { // if any employee's age over 30, then drop the dept
                    continue Outer // continue to Outer loop
                }
            }
        }
        result = append(result, dep)
    }
    return
}


執行印出結果如下,只印出部門編號2(Department.Id: 2)的資料。

[{2 Mkt. [{3 Bill 18} {4 Nick 17}]}]

第一次看到Outer:標註的位置還以為會跳出外面的迴圈,結果是continue到外面的for迴圈繼續執行。


沒有留言:

AdSense