以下代码展示了两种建立slice的方法。
我们可以使用sort函数给slice排序。
package mainimport ("fmt""sort"
)func main() {var fruitList = []string{"Apple", "Tomato", "Peach"}fmt.Printf("Type of fruitlist is %T\n", fruitList)fruitList = append(fruitList, "Mango", "Banana")fmt.Println(fruitList)fruitList = append(fruitList[:3])fmt.Println(fruitList)highScores := make([]int, 4)highScores[0] = 234highScores[1] = 945highScores[2] = 465highScores[3] = 867highScores = append(highScores, 555, 666, 321)fmt.Println(highScores)fmt.Println(sort.IntsAreSorted(highScores))sort.Ints(highScores)fmt.Println((highScores))
}
输出为:
Type of fruitlist is []string
[Apple Tomato Peach Mango Banana]
[Apple Tomato Peach]
[234 945 465 867 555 666 321]
false
[234 321 465 555 666 867 945]
以下代码展示了如何根据index从slice中移除指定元素。
package mainimport ("fmt"
)func main() {var courses = []string{"reactjs", "javascript", "swift", "python", "ruby"}fmt.Println(courses)var index int = 2courses = append(courses[:index], courses[index+1:]...)fmt.Println(courses)
}