// 原地删除,公用底层数组 s := []string{"a", "b", " ", "d", "e", " ", "f"} b := s[:0] for _, x := range s { if x != " " { b = append(b, x) // append函数用于追加元素 } } fmt.Println(b)
slice作为参数
1 2 3 4 5 6 7
// more本质上就是slice类型 func Sum(a int, more ...int) int { for _, v := range more { a += v } return a }
package main
import "fmt"
type Element interface{} type List []Element type People struct { Name string }
func main() { list := make(List, 3) list[0] = 1 list[1] = "hello" list[2] = People{"test"} for _, value := range list { n, ok := value.(int) if ok { fmt.Println(n) continue } s, ok := value.(string) if ok { fmt.Println(s[:3]) continue } p, ok := value.(People) if ok { fmt.Println(p.Name) continue } } }
package main
import "fmt"
type Element interface{} type List []Element type People struct { Name string }
func main() { list := make(List, 4) list[0] = 1 list[1] = "hello" list[2] = People{"test"} list[3] = 2.3 for _, value := range list { switch t := value.(type) { case int: fmt.Println(t + 1) case string: fmt.Println(t[:3]) case People: fmt.Println(t.Name) default: fmt.Println("类型异常") } } }