慕姐8265434
例如,package mainimport "fmt"type Person struct { Age int Name string}var people = []Person{{Age: 18, Name: "Deb"}, {Age: 22, Name: "Bob"}, {Age: 35, Name: "Bob"}}func findPerson(people []Person, name string) (Person, bool) { for _, p := range people { if p.Name == name { return p, true } } return Person{}, false}func main() { FirstBob, found := findPerson(people, "Bob") if found { fmt.Println(FirstBob) }}输出:{22 Bob}如果你想返回一个指向Person结构的指针,package mainimport "fmt"type Person struct { Age int Name string}var people = []Person{{Age: 18, Name: "Deb"}, {Age: 22, Name: "Bob"}, {Age: 35, Name: "Bob"}}func findPerson(people []Person, name string) (*Person, bool) { for i := range people { p := &people[i] if p.Name == name { return p, true } } return nil, false}func main() { FirstBob, found := findPerson(people, "Bob") if found { fmt.Println(*FirstBob) }}输出:{22 Bob}