數組去重 查找元素 數組降序 迭代數組 將map轉為數組 合併數組 合併map 判斷map中key是否存在 ...
數組去重
package main
import "fmt"
func main(){
intSlice := []int{1,5,5,5,5,7,8,6,6, 6}
fmt.Println(intSlice)
uniqueIntSlice := unique(intSlice)
fmt.Println(uniqueIntSlice)
}
func unique(intSlice []int) []int{
keys := make(map[int]bool)
uniqueElements := []int{}
for _,entry := range intSlice {
if _, value := keys[entry]; !value{
keys[entry] =true
uniqueElements = append(uniqueElements, entry)
}
}
return uniqueElements
}
查找元素
package main
import (
"fmt"
"sort"
)
func main() {
str := []string{"Sandy", "Provo", "St.george", "Salt lake City", "Draper", "South Jordan", "Murray"}
// for迴圈查找
for i, v := range str {
if v == "Sandy" {
fmt.Println(i)
}
}
// sort包排序後查找
// StringSlice給[]string添加方法以滿足Interface介面,以便排序為遞增序列。
sortedList := sort.StringSlice(str)
// 升序
sortedList.Sort()
fmt.Println(sortedList)
index := sortedList.Search("Sandy")
fmt.Println(index)
}
數組降序
package main
import (
"sort"
"fmt"
)
func main() {
numbers := []int{1, 5, 3, 6, 2, 10, 8}
// IntSlice給[]int添加方法以滿足Interface介面,以便排序為遞增序列。
tobeSorted := sort.IntSlice(numbers)
// Reverse包裝一個Interface介面並返回一個新的Interface介面,對該介面排序可生成遞減序列。
sort.Sort(sort.Reverse(tobeSorted))
fmt.Println(tobeSorted)
}
迭代數組
package main
import "fmt"
func main(){
numbers := []int{1, 5, 3, 6, 2, 10, 8}
for index,value := range numbers{
fmt.Printf("Index: %v and Value: %v\n", index, value)
}
}
將map轉為數組
package main
import "fmt"
type NameAge struct{
Name string
Age int
}
func main(){
var nameAgeSlice []NameAge
nameAges := map[string]int{
"Michael": 30,
"John": 25,
"Jessica": 26,
"Ali": 18,
}
for key, value := range nameAges{
nameAgeSlice = append(nameAgeSlice, NameAge {key, value})
}
fmt.Println(nameAgeSlice)
}
合併數組
package main
import "fmt"
func main(){
items1 := []int{3,4}
items2 := []int{1,2}
result := append(items1, items2...)
fmt.Println(result)
}
合併map
package main
import "fmt"
func main(){
map1 := map[string]int {
"Michael":10,
"Jessica":20,
"Tarik":33,
"Jon": 22,
}
fmt.Println(map1)
map2 := map[string]int {
"Lord":11,
"Of":22,
"The":36,
"Rings": 23,
}
for key, value := range map2{
map1[key] = value
}
fmt.Println(map1)
}
判斷map中key是否存在
package main
import "fmt"
func main() {
nameAges := map[string]int{
"Tarik": 32,
"Michael": 30,
"Jon": 25,
"Jessica" : 20,
}
if _, exists := nameAges["Jessica"]; exists{
fmt.Println("Jessica can be found")
}else {
fmt.Println("Jessica cannot be found")
}
}