網頁

2022/11/15

Golang 尋找slice的struct元素

Go尋找slice中物件元素。


範例環境:

  • Go 1.19

例如以名稱尋找Department.Employees slice中的struct Employee元素。

main.go

package main

import "fmt"

type Department struct {
    Employees []Employee
}

type Employee struct {
    ID   int
    Name string
}

func (dep *Department) FindEmployee(name string) *Employee {
    for _, v := range dep.Employees {
        if v.Name == name {
            return &v
        }
    }
    return nil
}

func main() {
    dep := Department{
        Employees: []Employee{
            {1, "John"},
            {2, "Mary"},
            {3, "Tony"},
        },
    }

    fmt.Println(dep.FindEmployee("Mary").ID) // 2
}

沒有留言:

張貼留言