以下代码展示了两种建立slice的方法。
我们可以使用sort函数给slice排序。文章来源:https://www.toymoban.com/news/detail-681838.html
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]文章来源地址https://www.toymoban.com/news/detail-681838.html
以下代码展示了如何根据index从slice中移除指定元素。
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)
}
到了这里,关于Go 自学:切片slices的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!