接口类型断言,方法参数传递
2021-04-24 本文已影响0人
郭青耀
实现移除某姓名或者某一年龄的人:
package main
import (
"errors"
"fmt"
)
type student struct {
Name string
Age int
}
type StudentSlice []student
func (s *StudentSlice) Remove(element interface{}) error {
for i, v := range *s {
if value, ok := element.(int); ok {
if v.Age == value {
*s = append((*s)[:i], (*s)[i+1:]...)
}
continue
} else if value, ok := element.(string); ok {
if v.Name == value {
*s = append((*s)[:i], (*s)[i+1:]...)
}
continue
} else {
fmt.Println("type error")
return errors.New("Not Found.")
}
}
return nil
}
func main() {
students := StudentSlice{
{Name: "zhou", Age: 24},
{Name: "li", Age: 23},
{Name: "wang", Age: 22},
}
students.Remove("li")
students.Remove(22)
fmt.Println(students)
}