2 回答
TA贡献1813条经验 获得超2个赞
例如,
package main
import "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 main
import "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}
- 2 回答
- 0 关注
- 176 浏览
添加回答
举报