以下代码展示了两种建立slice的方法。
我们可以使用sort函数给slice排序。
go
package main
import (
"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] = 234
highScores[1] = 945
highScores[2] = 465
highScores[3] = 867
highScores = 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中移除指定元素。
go
package main
import (
"fmt"
)
func main() {
var courses = []string{"reactjs", "javascript", "swift", "python", "ruby"}
fmt.Println(courses)
var index int = 2
courses = append(courses[:index], courses[index+1:]...)
fmt.Println(courses)
}