切片排序或搜索功能允许您以各种方式与切片进行交互和操作。Golang排序函数是核心的一部分。使用此功能无需安装,只需导入"sort"包即可。借助排序功能,您可以搜索任何重要的Golang排序函数列表如下:
Ints函数按升序对整数切片进行排序。
func Ints(intSlice []int)
示例代码:
package main
import (
"fmt"
"sort"
)
func main() {
intSlice := []int{10, 5, 25, 351, 14, 9} // unsorted
fmt.Println("Slice of integer BEFORE sort:",intSlice)
sort.Ints(intSlice)
fmt.Println("Slice of integer AFTER sort:",intSlice)
}
输出:
Slice of integer BEFORE sort: [10 5 25 351 14 9]
Slice of integer AFTER sort: [5 9 10 14 25 351]
Strings函数按字典升序对字符串切片进行排序。
func Strings(strSlice []string)
示例代码:
package main
import (
"fmt"
"sort"
)
func main() {
strSlice := []string{"Jamaica","Estonia","Indonesia","Hong Kong"} // unsorted
fmt.Println("Slice of string BEFORE sort:",strSlice)
sort.Strings(strSlice)
fmt.Println("Slice of string AFTER sort:",strSlice)
fmt.Println("\n-----------------------------------\n")
strSlice = []string{"JAMAICA","Estonia","indonesia","hong Kong"} // unsorted
fmt.Println("Slice of string BEFORE sort:",strSlice)
sort.Strings(strSlice)
fmt.Println("Slice of string AFTER sort:",strSlice)
}
输出:
Slice of string BEFORE sort: [Jamaica Estonia Indonesia Hong Kong]
Slice of string AFTER sort: [Estonia Hong Kong Indonesia Jamaica]
-----------------------------------
Slice of string BEFORE sort: [JAMAICA Estonia indonesia hong Kong]
Slice of string AFTER sort: [Estonia JAMAICA hong Kong indonesia]
Float64s函数按升序对float64的切片进行排序。
func Float64s(fltSlice []string)
示例代码:
package main
import (
"fmt"
"sort"
)
func main() {
fltSlice := []float64{18787677.878716, 565435.321, 7888.545, 8787677.8716, 987654.252} // unsorted
fmt.Println("Slice BEFORE sort: ",fltSlice)
sort.Float64s(fltSlice)
fmt.Println("Slice AFTER sort: ",fltSlice)
}
输出:
Slice BEFORE sort: [1.8787677878716e+07 565435.321 7888.545 8.7876778716e+06 987654.252]
Slice AFTER sort: [7888.545 565435.321 987654.252 8.7876778716e+06 1.8787677878716e+07]
IntsAreSorted函数测试整数切片是否按升序排序。如果按升序找到数字切片,则返回true,否则返回false。
func IntsAreSorted(a []string) bool
示例代码:
package main
import (
"fmt"
"sort"
)
func main() {
intSlice := []int{10, 5, 25, 351, 14, 9} // unsorted
fmt.Println(sort.IntsAreSorted(intSlice)) // false
intSlice = []int{5, 9, 14, 351, 614, 999} // sorted
fmt.Println(sort.IntsAreSorted(intSlice)) // true
}
输出:
false
true
StringsAreSorted函数测试字符串切片是否按升序排序。如果按升序找到字符串切片,则返回true,否则返回false。
func StringsAreSorted(strSlice []string) bool
示例代码:
package main
import (
"fmt"
"sort"
)
func main() {
strSlice := []string{"Jamaica","Estonia","Indonesia","Hong Kong"} // unsorted
fmt.Println(sort.StringsAreSorted(strSlice)) // false
strSlice = []string{"JAMAICA","Estonia","indonesia","hong Kong"} // unsorted
fmt.Println(sort.StringsAreSorted(strSlice)) // false
strSlice = []string{"estonia","hong Kong","indonesia","jamaica"} // sorted
fmt.Println(sort.StringsAreSorted(strSlice)) // true
}
输出:
false
false
true
Float64sAreSorted函数测试float64s的切片是否按升序排序。如果按升序找到float64的切片,则返回true,否则返回false。
func Float64sAreSorted(fltSlice []float64) bool
示例代码:
package main
import (
"fmt"
"sort"
)
func main() {
fltSlice := []float64{18787677.878716, 565435.321, 7888.545, 8787677.8716, 987654.252} // unsorted
fmt.Println(sort.Float64sAreSorted(fltSlice)) // false
fltSlice = []float64{565435.321, 887888.545, 8787677.8716, 91187654.252} // sorted
fmt.Println(sort.Float64sAreSorted(fltSlice)) // true
}
输出:
false
true
SearchInts函数在int的排序切片中搜索x的位置,并返回Search指定的索引。如果切片仅按排序顺序排列,则此函数有效。如果在intSlice中找到x,则返回intSlice的索引位置,否则返回x适合排序切片的索引位置。以下示例显示了SearchInts() 函数的用法:
func SearchInts(intSlice []int, x int) int
示例代码:
package main
import (
"fmt"
"sort"
)
func main() {
// integer slice in unsort order
intSlice := []int{55, 22, 18, 9, 12, 82, 28, 36, 45, 65}
x := 18
pos := sort.SearchInts(intSlice,x)
fmt.Printf("Found %d at index %d in %v\n", x, pos, intSlice)
// slice need to be sort in ascending order before to use SearchInts
sort.Ints(intSlice) // slice sorted
pos = sort.SearchInts(intSlice,x)
fmt.Printf("Found %d at index %d in %v\n", x, pos, intSlice)
x = 54
pos = sort.SearchInts(intSlice,x)
fmt.Printf("Found %d at index %d in %v\n", x, pos, intSlice)
x = 99
pos = sort.SearchInts(intSlice,x)
fmt.Printf("Found %d at index %d in %v\n", x, pos, intSlice)
x = -5
pos = sort.SearchInts(intSlice,x)
fmt.Printf("Found %d at index %d in %v\n", x, pos, intSlice)
}
输出:
Found 18 at index 0 in [55 22 18 9 12 82 28 36 45 65]
Found 18 at index 2 in [9 12 18 22 28 36 45 55 65 82]
Found 54 at index 7 in [9 12 18 22 28 36 45 55 65 82]
Found 99 at index 10 in [9 12 18 22 28 36 45 55 65 82]
Found -5 at index 0 in [9 12 18 22 28 36 45 55 65 82]
SearchStrings函数在排序的字符串切片中搜索x的位置,并返回Search指定的索引。如果切片仅按排序顺序排列,则此函数有效。如果在strSlice中找到x,则返回strSlice的索引位置,否则返回索引位置,其中x适合排序切片。以下示例显示了SearchStrings() 函数的用法:
func SearchStrings(strSlice []string, x string) int
示例代码:
package main
import (
"fmt"
"sort"
)
func main() {
// string slice in unsorted order
strSlice := []string{"Texas","Washington","Montana","Alaska","Indiana","Ohio","Nevada"}
x := "Montana"
pos := sort.SearchStrings(strSlice,x)
fmt.Printf("Found %s at index %d in %v\n", x, pos, strSlice)
// slice need to be sort in ascending order before to use SearchStrings
sort.Strings(strSlice) // slice sorted
pos = sort.SearchStrings(strSlice,x)
fmt.Printf("Found %s at index %d in %v\n", x, pos, strSlice)
x = "Missouri"
pos = sort.SearchStrings(strSlice,x)
fmt.Printf("Found %s at index %d in %v\n", x, pos, strSlice)
x = "Utah"
pos = sort.SearchStrings(strSlice,x)
fmt.Printf("Found %s at index %d in %v\n", x, pos, strSlice)
x = "Ohio"
pos = sort.SearchStrings(strSlice,x)
fmt.Printf("Found %s at index %d in %v\n", x, pos, strSlice)
x = "OHIO"
pos = sort.SearchStrings(strSlice,x)
fmt.Printf("Found %s at index %d in %v\n", x, pos, strSlice)
x = "ohio"
pos = sort.SearchStrings(strSlice,x)
fmt.Printf("Found %s at index %d in %v\n", x, pos, strSlice)
}
输出:
Found Montana at index 5 in [Texas Washington Montana Alaska Indiana Ohio Nevada]
Found Montana at index 2 in [Alaska Indiana Montana Nevada Ohio Texas Washington]
Found Missouri at index 2 in [Alaska Indiana Montana Nevada Ohio Texas Washington]
Found Utah at index 6 in [Alaska Indiana Montana Nevada Ohio Texas Washington]
Found Ohio at index 4 in [Alaska Indiana Montana Nevada Ohio Texas Washington]
Found OHIO at index 4 in [Alaska Indiana Montana Nevada Ohio Texas Washington]
Found ohio at index 7 in [Alaska Indiana Montana Nevada Ohio Texas Washington]
SearchFloat64s函数在float64的排序切片中搜索x的位置,并返回Search指定的索引。如果切片仅按排序顺序排列,则此函数有效。如果在fltSlice中找到x,则返回fltSlice的索引位置,否则返回x适合排序切片的索引位置。以下示例显示了SearchFloat64s() 函数的用法:
func SearchFloat64s(fltSlice []float64, x float64)
示例代码:
package main
import (
"fmt"
"sort"
)
func main() {
// string slice in unsorted order
fltSlice := []float64{962.25, 514.251, 141.214, 96.142, 85.14}
x := 141.214
pos := sort.SearchFloat64s(fltSlice,x)
fmt.Printf("Found %f at index %d in %v\n", x, pos, fltSlice)
// slice need to be sort in ascending order before to use SearchFloat64s
sort.Float64s(fltSlice) // slice sorted
pos = sort.SearchFloat64s(fltSlice,x)
fmt.Printf("Found %f at index %d in %v\n", x, pos, fltSlice)
x = 8989.251
pos = sort.SearchFloat64s(fltSlice,x)
fmt.Printf("Found %f at index %d in %v\n", x, pos, fltSlice)
x = 10.251
pos = sort.SearchFloat64s(fltSlice,x)
fmt.Printf("Found %f at index %d in %v\n", x, pos, fltSlice)
x = 411.251
pos = sort.SearchFloat64s(fltSlice,x)
fmt.Printf("Found %f at index %d in %v\n", x, pos, fltSlice)
x = -411.251
pos = sort.SearchFloat64s(fltSlice,x)
fmt.Printf("Found %f at index %d in %v\n", x, pos, fltSlice)
}
输出:
Found 141.214000 at index 0 in [962.25 514.251 141.214 96.142 85.14]
Found 141.214000 at index 2 in [85.14 96.142 141.214 514.251 962.25]
Found 8989.251000 at index 5 in [85.14 96.142 141.214 514.251 962.25]
Found 10.251000 at index 0 in [85.14 96.142 141.214 514.251 962.25]
Found 411.251000 at index 3 in [85.14 96.142 141.214 514.251 962.25]
Found -411.251000 at index 0 in [85.14 96.142 141.214 514.251 962.25]
Search函数在string/float/int的排序切片中搜索x的位置,并返回Search指定的索引。如果在数据中找到x,则返回数据的索引位置,否则返回索引位置,其中x适合排序切片。此功能适用于升序和降序切片,而以上3个搜索功能仅适用于升序。以下示例显示了Search() 函数的用法:
sort.Search(len(data), func(i int) bool { return data[i] >= x })
示例代码:
package main
import (
"fmt"
"sort"
)
func main() {
fmt.Println("\n######## SearchInts not works in descending order ######## ")
intSlice := []int{55, 54, 53, 52, 51, 50, 48, 36, 15, 5} // sorted slice in descending
x := 36
pos := sort.SearchInts(intSlice,x)
fmt.Printf("Found %d at index %d in %v\n", x, pos, intSlice)
fmt.Println("\n######## Search works in descending order ########")
i := sort.Search(len(intSlice), func(i int) bool { return intSlice[i] <= x })
fmt.Printf("Found %d at index %d in %v\n", x, i, intSlice)
fmt.Println("\n\n######## SearchStrings not works in descending order ######## ")
// sorted slice in descending
strSlice := []string{"Washington","Texas","Ohio","Nevada","Montana","Indiana","Alaska"}
y := "Montana"
posstr := sort.SearchStrings(strSlice,y)
fmt.Printf("Found %s at index %d in %v\n", y, posstr, strSlice)
fmt.Println("\n######## Search works in descending order ########")
j := sort.Search(len(strSlice), func(j int) bool {return strSlice[j] <= y})
fmt.Printf("Found %s at index %d in %v\n", y, j, strSlice)
fmt.Println("\n######## Search works in ascending order ########")
fltSlice := []float64{10.10, 20.10, 30.15, 40.15, 58.95} // string slice in float64
z := 40.15
k := sort.Search(len(fltSlice), func(k int) bool {return fltSlice[k] >= z})
fmt.Printf("Found %f at index %d in %v\n", z, k, fltSlice)
}
输出:
######## SearchInts not works in descending order ########
Found 36 at index 0 in [55 54 53 52 51 50 48 36 15 5]
######## Search works in descending order ########
Found 36 at index 7 in [55 54 53 52 51 50 48 36 15 5]
######## SearchStrings not works in descending order ########
Found Montana at index 0 in [Washington Texas Ohio Nevada Montana Indiana Alaska]
######## Search works in descending order ########
Found Montana at index 4 in [Washington Texas Ohio Nevada Montana Indiana Alaska]
######## Search works in ascending order ########
Found 40.150000 at index 3 in [10.1 20.1 30.15 40.15 58.95]
Sort函数按升序和降序对数据接口进行排序。它首先调用数据。Len用于确定n,O(n*log(n)) 调用数据。更少和数据。交换。以下示例显示了Sort() 函数的用法:
func Sort(data Interface)
示例代码:
package main
import (
"fmt"
"sort"
)
type Mobile struct {
Brand string
Price int
}
// ByPrice implements sort.Interface for []Mobile based on
// the Price field.
type ByPrice []Mobile
func (a ByPrice) Len() int { return len(a) }
func (a ByPrice) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func (a ByPrice) Less(i, j int) bool { return a[i].Price < a[j].Price }
// ByBrand implements sort.Interface for []Mobile based on
// the Brand field.
type ByBrand []Mobile
func (a ByBrand) Len() int { return len(a) }
func (a ByBrand) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func (a ByBrand) Less(i, j int) bool { return a[i].Brand > a[j].Brand }
func main() {
mobile := []Mobile{
{"Sony", 952},
{"Nokia", 468},
{"Apple", 1219},
{"Samsung", 1045},
}
fmt.Println("\n######## Before Sort #############\n")
for _, v := range mobile {
fmt.Println(v.Brand, v.Price)
}
fmt.Println("\n\n######## Sort By Price [ascending] ###########\n")
sort.Sort(ByPrice(mobile))
for _, v := range mobile {
fmt.Println(v.Brand, v.Price)
}
fmt.Println("\n\n######## Sort By Brand [descending] ###########\n")
sort.Sort(ByBrand(mobile))
for _, v := range mobile {
fmt.Println(v.Brand, v.Price)
}
}
输出:
######## Before Sort #############
Sony 952
Nokia 468
Apple 1219
Samsung 1045
######## Sort By Price [ascending] ###########
Nokia 468
Sony 952
Samsung 1045
Apple 1219
######## Sort By Brand [descending] ###########
Sony 952
Samsung 1045
Nokia 468
Apple 1219
IsSorted函数报告数据排序依据是返回true还是false。以下示例显示了IsSorted() 函数的用法:
func IsSorted(data Interface) bool
示例代码:
package main
import (
"fmt"
"sort"
)
type Mobile struct {
Brand string
Price int
}
// ByPrice implements sort.Interface for []Mobile based on
// the Price field.
type ByPrice []Mobile
func (a ByPrice) Len() int { return len(a) }
func (a ByPrice) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func (a ByPrice) Less(i, j int) bool { return a[i].Price < a[j].Price }
func main() {
mobile1 := []Mobile{
{"Sony", 952},
{"Nokia", 468},
{"Apple", 1219},
{"Samsung", 1045},
}
fmt.Println("\nFound mobile1 price is sorted :", sort.IsSorted(ByPrice(mobile1))) // false
mobile2 := []Mobile{
{"Sony", 452},
{"Nokia", 768},
{"Apple", 919},
{"Samsung", 1045},
}
fmt.Println("\nFound mobile2 price is sorted :", sort.IsSorted(ByPrice(mobile2))) // true
}
输出:
Found mobile1 price is sorted : false
Found mobile2 price is sorted : true
Slice函数根据提供的less函数对提供的切片进行排序。如果提供的接口不是切片,则该函数会崩溃。以下示例显示了Slice() 函数的用法:
func Slice(slice interface{}, less func(i, j int) bool)
示例代码:
package main
import (
"fmt"
"sort"
)
func main() {
mobile := []struct {
Brand string
Price int
}{
{"Nokia", 700},
{"Samsung", 505},
{"Apple", 924},
{"Sony", 655},
}
sort.Slice(mobile, func(i, j int) bool { return mobile[i].Brand < mobile[j].Brand })
fmt.Println("\n\n######## Sort By Brand [ascending] ###########\n")
for _, v := range mobile {
fmt.Println(v.Brand, v.Price)
}
sort.Slice(mobile, func(i, j int) bool { return mobile[i].Brand > mobile[j].Brand })
fmt.Println("\n\n######## Sort By Brand [descending] ###########\n")
for _, v := range mobile {
fmt.Println(v.Brand, v.Price)
}
sort.Slice(mobile, func(i, j int) bool { return mobile[i].Price < mobile[j].Price })
fmt.Println("\n\n######## Sort By Price [ascending] ###########\n")
for _, v := range mobile {
fmt.Println(v.Brand, v.Price)
}
mobile = []struct {
Brand string
Price int
}{
{"MI", 900},
{"OPPO", 305},
{"iPhone", 924},
{"sony", 655},
}
sort.Slice(mobile, func(i, j int) bool { return mobile[i].Brand < mobile[j].Brand })
fmt.Println("\n\n######## Sort By Brand [ascending] ###########\n")
for _, v := range mobile {
fmt.Println(v.Brand, v.Price)
}
}
输出:
######## Sort By Brand [ascending] ###########
Apple 924
Nokia 700
Samsung 505
Sony 655
######## Sort By Brand [descending] ###########
Sony 655
Samsung 505
Nokia 700
Apple 924
######## Sort By Price [ascending] ###########
Samsung 505
Sony 655
Nokia 700
Apple 924
######## Sort By Brand [ascending] ###########
MI 900
OPPO 305
iPhone 924
sony 655
此SliceIsSorted函数测试切片是否已排序。如果数据已排序,则返回true或false。以下示例显示了SliceIsSorted() 函数的用法:
func SliceIsSorted(slice interface{}, less func(i, j int) bool) bool
示例代码:
package main
import (
"fmt"
"sort"
)
func main() {
mobile := []struct {
Brand string
Price int
}{
{"Nokia", 700},
{"Samsung", 505},
{"Apple", 924},
{"Sony", 655},
}
result := sort.SliceIsSorted(mobile, func(i, j int) bool { return mobile[i].Price < mobile[j].Price })
fmt.Println("Found price sorted:", result) // false
mobile = []struct {
Brand string
Price int
}{
{"Nokia", 700},
{"Samsung", 805},
{"Apple", 924},
{"Sony", 955},
}
result = sort.SliceIsSorted(mobile, func(i, j int) bool { return mobile[i].Price < mobile[j].Price })
fmt.Println("Found price sorted:", result) // true
mobile = []struct {
Brand string
Price int
}{
{"iPhone", 900},
{"MI", 805},
{"OPPO", 724},
{"Sony", 655},
}
result = sort.SliceIsSorted(mobile, func(i, j int) bool { return mobile[i].Brand < mobile[j].Brand })
fmt.Println("Found brand sorted:", result) // false
}
输出:
Found price sorted: false
Found price sorted: true
Found brand sorted: false
IntSlice将Interface的方法附加到 []int,并按递增顺序排序。Len曾经找到切片的长度。Search返回将SearchInts应用于接收器和x的结果。排序 用于对切片进行排序。 以下示例显示了IntSlice() 函数的用法:
type IntSlice []int
示例代码:
package main
import (
"fmt"
"sort"
)
func main() {
s := []int{9, 22, 54, 33, -10, 40} // unsorted
sort.Sort(sort.IntSlice(s))
fmt.Println(s) // sorted
fmt.Println("Length of Slice: ", sort.IntSlice.Len(s)) // 6
fmt.Println("40 found in Slice at position: ", sort.IntSlice(s).Search(40)) // 4
fmt.Println("82 found in Slice at position: ", sort.IntSlice(s).Search(82)) // 6
fmt.Println("6 found in Slice at position: ", sort.IntSlice(s).Search(6)) // 0
}
输出:
[-10 9 22 33 40 54]
Length of Slice: 6
40 found in Slice at position: 4
82 found in Slice at position: 6
6 found in Slice at position: 1
StringSlice将Interface的方法附加到 []string,并按递增顺序排序。Len曾经找到切片的长度。Search返回将SearchStrings应用于接收方和x的结果。排序 用于对切片进行排序。以下示例显示了StringSlice函数的用法:
type StringSlice []string
示例代码:
package main
import (
"fmt"
"sort"
)
func main() {
s := []string{"Washington","Texas","Ohio","Nevada","Montana","Indiana","Alaska"} // unsorted
sort.Sort(sort.StringSlice(s))
fmt.Println(s) // sorted
fmt.Println("Length of Slice: ", sort.StringSlice.Len(s)) // 7
fmt.Println("Texas found in Slice at position: ", sort.StringSlice(s).Search("Texas")) // 5
fmt.Println("Montana found in Slice at position: ", sort.StringSlice(s).Search("Montana")) // 2
fmt.Println("Utah found in Slice at position: ", sort.StringSlice(s).Search("Utah")) // 6
fmt.Println("OHIO found in Slice at position: ", sort.StringSlice(s).Search("OHIO")) // 4
fmt.Println("Ohio found in Slice at position: ", sort.StringSlice(s).Search("Ohio")) // 4
fmt.Println("ohio found in Slice at position: ", sort.StringSlice(s).Search("ohio")) // 7
}
输出:
[Alaska Indiana Montana Nevada Ohio Texas Washington]
Length of Slice: 7
Texas found in Slice at position: 5
Montana found in Slice at position: 2
Utah found in Slice at position: 6
OHIO found in Slice at position: 4
Ohio found in Slice at position: 4
ohio found in Slice at position: 7
Float64Slice将Interface的方法附加到 []float64,并按递增顺序排序。Len曾经找到切片的长度。Search返回将SearchFloat64s应用于接收器和x的结果。排序 用于对切片进行排序。以下示例显示了Float64Slice函数的用法:
type Float64Slice []float64
示例代码:
package main
import (
"fmt"
"sort"
)
func main() {
s := []float64{85.201, 14.74, 965.25, 125.32, 63.14} // unsorted
sort.Sort(sort.Float64Slice(s))
fmt.Println(s) // sorted
fmt.Println("Length of Slice: ", sort.Float64Slice.Len(s)) // 5
fmt.Println("123.32 found in Slice at position: ", sort.Float64Slice(s).Search(125.32)) // 3
fmt.Println("999.15 found in Slice at position: ", sort.Float64Slice(s).Search(999.15)) // 5
fmt.Println("12.14 found in Slice at position: ", sort.Float64Slice(s).Search(12.14)) // 0
}
输出:
[14.74 63.14 85.201 125.32 965.25]
Length of Slice: 5
123.32 found in Slice at position: 3
999.15 found in Slice at position: 5
12.14 found in Slice at position: 0
Reverse函数以相反的顺序返回切片。以下示例显示了Reverse() 函数的用法:
func Reverse(data Interface) Interface
示例代码:
package main
import (
"fmt"
"sort"
)
func main() {
a := []int{15, 4, 33, 52, 551, 90, 8, 16, 15, 105} // unsorted
sort.Sort(sort.Reverse(sort.IntSlice(a)))
fmt.Println("\n",a)
a = []int{-15, -4, -33, -52, -551, -90, -8, -16, -15, -105} // unsorted
sort.Sort(sort.Reverse(sort.IntSlice(a)))
fmt.Println("\n",a)
b := []string{"Montana","Alaska","Indiana","Nevada","Washington","Ohio","Texas"} // unsorted
sort.Sort(sort.Reverse(sort.StringSlice(b)))
fmt.Println("\n",b)
b = []string{"ALASKA","indiana","OHIO","Nevada","Washington","TEXAS","Montana"} // unsorted
sort.Sort(sort.Reverse(sort.StringSlice(b)))
fmt.Println("\n",b)
c := []float64{90.10, 80.10, 160.15, 40.15, 8.95} // unsorted
sort.Sort(sort.Reverse(sort.Float64Slice(c)))
fmt.Println("\n",c)
c = []float64{-90.10, -80.10, -160.15, -40.15, -8.95} // unsorted
sort.Sort(sort.Reverse(sort.Float64Slice(c)))
fmt.Println("\n",c)
}
输出:
[551 105 90 52 33 16 15 15 8 4]
[-4 -8 -15 -15 -16 -33 -52 -90 -105 -551]
[Washington Texas Ohio Nevada Montana Indiana Alaska]
[indiana Washington TEXAS OHIO Nevada Montana ALASKA]
[160.15 90.1 80.1 40.15 8.95]
[-8.95 -40.15 -80.1 -90.1 -160.15]
示例代码:
package main
import (
"fmt"
"math/rand"
)
type LuckyNumber struct {
number int
}
type Person struct {
lucky_numbers []LuckyNumber
}
func main() {
tmp := make([]LuckyNumber, 10)
for i := range tmp {
tmp[i].number = rand.Intn(100)
}
a := Person{tmp}
fmt.Println(a)
}
输出:
{[{81} {87} {47} {59} {81} {18} {25} {40} {56} {0}]}
示例代码:
package main
import (
"fmt"
)
type Widget struct {
id int
attrs []string
}
func main() {
widgets := []Widget{
Widget{
id: 10,
attrs: []string{"blah", "foo"},
},
Widget{
id: 11,
attrs: []string{"foo", "bar"},
},
Widget{
id: 12,
attrs: []string{"xyz"},
},
}
for _, j := range widgets {
fmt.Printf("%d ", j.id)
for _, y := range j.attrs {
fmt.Printf(" %s ", y)
}
fmt.Println()
}
}
输出:
10 blah foo
11 foo bar
12 xyz
切片是一种灵活且可扩展的数据结构,用于实现和管理数据集合。切片由多个元素组成,所有元素的类型相同。切片是动态数组的一段,可以根据需要增长和收缩。与数组一样,切片是可索引的并且具有长度。切片具有容量和长度属性。
创建空切片
若要声明包含切片的变量的类型,请使用一对空方括号,后跟切片将包含的元素类型。
package main
import (
"fmt"
"reflect"
)
func main() {
var intSlice []int
var strSlice []string
fmt.Println(reflect.ValueOf(intSlice).Kind())
fmt.Println(reflect.ValueOf(strSlice).Kind())
}
输出
slice
slice
使用make声明切片
Slice可以使用内置函数make创建。使用make时,一个选项是指定切片的长度。仅指定长度时,切片的容量是相同的。
package main
import (
"fmt"
"reflect"
)
func main() {
var intSlice = make([]int, 10) // 切片长度和容量相同
var strSlice = make([]string, 10, 20) // 切片长度和容量不同,20是容量
fmt.Printf("intSlice \tLen: %v \tCap: %v\n", len(intSlice), cap(intSlice))
fmt.Println(reflect.ValueOf(intSlice).Kind())
fmt.Printf("strSlice \tLen: %v \tCap: %v\n", len(strSlice), cap(strSlice))
fmt.Println(reflect.ValueOf(strSlice).Kind())
}
输出
intSlice Len: 10 Cap: 10
slice
strSlice Len: 10 Cap: 20
slice
值初始化切片
使用空括号,后跟切片将包含的元素类型,以及每个元素在大括号中具有的初始值的列表。
package main
import "fmt"
func main() {
var intSlice = []int{10, 20, 30, 40}
var strSlice = []string{"India", "Canada", "Japan"}
fmt.Printf("intSlice \tLen: %v \tCap: %v\n", len(intSlice), cap(intSlice))
fmt.Printf("strSlice \tLen: %v \tCap: %v\n", len(strSlice), cap(strSlice))
}
使用new关键字声明切片
可以使用new关键字声明切片,后跟方括号中的容量,然后是切片将包含的元素类型。
package main
import (
"fmt"
"reflect"
)
func main() {
var intSlice = new([50]int)[0:10]
fmt.Println(reflect.ValueOf(intSlice).Kind())
fmt.Printf("intSlice \tLen: %v \tCap: %v\n", len(intSlice), cap(intSlice))
fmt.Println(intSlice)
}
输出
slice
intSlice Len: 10 Cap: 50
[0 0 0 0 0 0 0 0 0 0]
添加元素
若要将项添加到切片的末尾,请使用append()方法。
package main
import "fmt"
func main() {
a := make([]int, 2, 5)
a[0] = 10
a[1] = 20
fmt.Println("Slice A:", a)
fmt.Printf("Length is %d Capacity is %d\n", len(a), cap(a))
a = append(a, 30, 40, 50, 60, 70, 80, 90)
fmt.Println("Slice A after appending data:", a)
fmt.Printf("Length is %d Capacity is %d\n", len(a), cap(a))
}
输出
Slice A: [10 20]
Length is 2 Capacity is 5
Slice A after appending data: [10 20 30 40 50 60 70 80 90]
Length is 9 Capacity is 12
如果基础切片中有足够的容量,则该元素将放置在最后一个元素之后,并且长度将增加。但是,如果容量不足,则会创建一个新切片,复制所有现有元素,将新元素添加到末尾,并返回新切片。
访问元素
您可以通过引用索引号来访问切片项目。
package main
import "fmt"
func main() {
var intSlice = []int{10, 20, 30, 40}
fmt.Println(intSlice[0])
fmt.Println(intSlice[1])
fmt.Println(intSlice[0:4])
}
更改元素值
package main
import "fmt"
func main() {
var strSlice = []string{"India", "Canada", "Japan"}
fmt.Println(strSlice)
strSlice[2] = "Germany"
fmt.Println(strSlice)
}
输出
[India Canada Japan]
[India Canada Germany]
从切片中删除元素
删除索引函数创建以从字符串切片中删除特定元素。
package main
import "fmt"
func main() {
var strSlice = []string{"India", "Canada", "Japan", "Germany", "Italy"}
fmt.Println(strSlice)
strSlice = RemoveIndex(strSlice, 3)
fmt.Println(strSlice)
}
func RemoveIndex(s []string, index int) []string {
return append(s[:index], s[index+1:]...)
}
输出
[India Canada Japan Germany Italy]
[India Canada Japan Italy]
复制切片
内置的copy功能用于将数据从一个切片复制到另一个切片。
package main
import "fmt"
func main() {
a := []int{5, 6, 7} // Create a smaller slice
fmt.Printf("[Slice:A] Length is %d Capacity is %d\n", len(a), cap(a))
b := make([]int, 5, 10) // Create a bigger slice
copy(b, a) // Copy function
fmt.Printf("[Slice:B] Length is %d Capacity is %d\n", len(b), cap(b))
fmt.Println("Slice B after copying:", b)
b[3] = 8
b[4] = 9
fmt.Println("Slice B after adding elements:", b)
}
输出
[Slice:A] Length is 3 Capacity is 3
[Slice:B] Length is 5 Capacity is 10
Slice B after copying: [5 6 7 0 0]
Slice B after adding elements: [5 6 7 8 9]
切片的技巧
切片是一种有条不紊地访问部分数据的快速方法。
package main
import "fmt"
func main() {
var countries = []string{"india", "japan", "canada", "australia", "russia"}
fmt.Printf("Countries: %v\n", countries)
fmt.Printf(":2 %v\n", countries[:2])
fmt.Printf("1:3 %v\n", countries[1:3])
fmt.Printf("2: %v\n", countries[2:])
fmt.Printf("2:5 %v\n", countries[2:5])
fmt.Printf("0:3 %v\n", countries[0:3])
fmt.Printf("Last element: %v\n", countries[4])
fmt.Printf("Last element: %v\n", countries[len(countries)-1])
fmt.Printf("Last element: %v\n", countries[4:])
fmt.Printf("All elements: %v\n", countries[0:len(countries)])
fmt.Printf("Last two elements: %v\n", countries[3:len(countries)])
fmt.Printf("Last two elements: %v\n", countries[len(countries)-2:len(countries)])
fmt.Println(countries[:])
fmt.Println(countries[0:])
fmt.Println(countries[0:len(countries)])
}
输出
Countries: [india japan canada australia russia]
:2 [india japan]
1:3 [japan canada]
2: [canada australia russia]
2:5 [canada australia russia]
0:3 [india japan canada]
Last element: russia
Last element: russia
Last element: [russia]
All elements: [india japan canada australia russia]
Last two elements: [australia russia]
Last two elements: [australia russia]
[india japan canada australia russia]
[india japan canada australia russia]
[india japan canada australia russia]
循环访问切片
可以使用for循环遍历列表项。
package main
import "fmt"
func main() {
var strSlice = []string{"India", "Canada", "Japan", "Germany", "Italy"}
fmt.Println("\n---------------Example 1 --------------------\n")
for index, element := range strSlice {
fmt.Println(index, "--", element)
}
fmt.Println("\n---------------Example 2 --------------------\n")
for _, value := range strSlice {
fmt.Println(value)
}
j := 0
fmt.Println("\n---------------Example 3 --------------------\n")
for range strSlice {
fmt.Println(strSlice[j])
j++
}
}
将切片追加到现有切片
...用于追加切片的省略号。
package main
import "fmt"
func main() {
var slice1 = []string{"india", "japan", "canada"}
var slice2 = []string{"australia", "russia"}
slice2 = append(slice2, slice1...)
}
检查元素是否存在
要确定切片中是否存在指定的项,请迭代切片项并检查使用if条件。
package main
import (
"fmt"
"reflect"
)
func main() {
var strSlice = []string{"India", "Canada", "Japan", "Germany", "Italy"}
fmt.Println(itemExists(strSlice, "Canada"))
fmt.Println(itemExists(strSlice, "Africa"))
}
func itemExists(slice interface{}, item interface{}) bool {
s := reflect.ValueOf(slice)
if s.Kind() != reflect.Slice {
panic("Invalid data-type")
}
for i := 0; i < s.Len(); i++ {
if s.Index(i).Interface() == item {
return true
}
}
return false
}