8.字符串和字节#

字符串和字节切片

bytes: 将buffer对象转换为字节切片

String: 将buffer对象转化为字符串

可以将string通过函数byte[]转化为字节切片,同时也可通过

8.1strings包介绍#

strings包提供操作UFT-8字符串常用函数

Compare: 比较字符串

Contains:是否包含子字符串

Count: 字符串出现次数

EqualFold: 不区分大小写比较

Fields: 按空白符分割字符串

Split: 分割字符串为切片

Join: 将字符串切片链接

LastIndex: 获取字符串最后一次出现的位置

Hasprefix: 是否以字符串作为某个字符串开头

HasSuffix: 是否以字符串作为某个字符串结尾

Index: 获取字符串首次出现

8.2strings常用操作#

package main
import (
    "fmt"
    "strings"
)
func main(){
    fmt.Println(strings.Compare("abc","bac"))
}

不相等则是-1,否则是0

[root@www.linuxea.com /opt/Golang/work2]# go run string.go 
-1

abc是否包含bc,包含则为true

fmt.Println(strings.Contains("abc","bc"))

运行

[root@www.linuxea.com /opt/Golang/work2]# go run string.go 
true

abcdsadasdasdas只要包含一个b就为true

fmt.Println(strings.Contains("abcdsadasdasdas","b"))
[root@www.linuxea.com /opt/Golang/work2]# go run string.go 
true

获取abcdsadasdasdas中a出现的次数

fmt.Println(strings.Count("abcdsadasdasdas","a"))
[root@www.linuxea.com /opt/Golang/work2]# go run string.go 
5

按空白字符分割

    fmt.Println(strings.Fields("abc def\n eeee"))
    fmt.Printf("%q\n",strings.Fields("abc def\n eeee"))
[root@www.linuxea.com /opt/Golang/work2]# go run string.go 
[abc def eeee]
["abc" "def" "eeee"]

HasPrefix是以什么开头,如果是就为true

HasSuffix是以什么结尾,如果是就为true

    fmt.Println(strings.HasPrefix("abcd","ab"))
    fmt.Println(strings.HasSuffix("abcd","cd"))
[root@www.linuxea.com /opt/Golang/work2]# go run string.go 
true
true

cd在abcd中的索引位置,如果存在则打印索引位置,如果不存在就等于-1

fmt.Println(strings.Index("abcd","cd"))
[root@www.linuxea.com /opt/Golang/work2]# go run string.go 
2

这里还有Lastindex,就是最后出现的索引位置

    fmt.Println(strings.LastIndex("abcdaasxcd","cd"))
[root@www.linuxea.com /opt/Golang/work2]# go run string.go
8
fmt.Println(strings.Split("adbcdef;abcd;abcd3edsa",";"))

以;进行分割

[root@www.linuxea.com /opt/Golang/work2]# go run string.go
[adbcdef abcd abcd3edsa]
fmt.Println(strings.Join([]string{"adb","abcd","abcd3edsa"},"~"))

以~进行链接

[root@www.linuxea.com /opt/Golang/work2]# go run string.go
adb~abcd~abcd3edsa
fmt.Println(strings.Repeat("abc",3))

将acb重复三次

[root@www.linuxea.com /opt/Golang/work2]# go run string.go
abcabcabc

将abcabcabcabc中的a替换成1,1表示替换一次

    fmt.Println(strings.Replace("abcabcabcabc","a","1",1))

将abcabcabcabc中的a替换成1,-1表示全部替换

    fmt.Println(strings.Replace("abcabcabcabc","a","1",-1))

将abcabcabcabc中的a替换成1,ReplaceAll不需要指定替换多少次,默认替换全部

    fmt.Println(strings.ReplaceAll("abcabcabcabc","a","1"))

运行

[root@www.linuxea.com /opt/Golang/work2]# go run string.go
1bcabcabcabc
1bc1bc1bc1bc
1bc1bc1bc1bc

ToLower转换小写,ToUpper转换大写

    fmt.Println(strings.ToLower("abcABC"))
    fmt.Println(strings.ToUpper("abcABC"))

运行

[root@www.linuxea.com /opt/Golang/work2]# go run string.go
abcabc
ABCABC
fmt.Println(strings.Title("hello"))

将hello首字母大写

[root@www.linuxea.com /opt/Golang/work2]# go run string.go
Hello
fmt.Println(strings.Trim("xhelloxz","xz"))

去掉xhelloxz前后包括xz或者前后包含x,z的字符

[root@www.linuxea.com /opt/Golang/work2]# go run string.go
hello
fmt.Println(strings.TrimSpace(" hello \n \r "))
[root@www.linuxea.com /opt/Golang/work2]# go run string.go
hello

8.3定义字节切片#

byte是无符号的uint8类型。

package main
import (
    "fmt"
)
func main(){
    var bytes []byte = []byte{'a','b','c'}
    fmt.Printf("%T,%#v\n",bytes,bytes)
}
[root@www.linuxea.com /opt/Golang/work2]# go run byte.go 
[]uint8,[]byte{0x61, 0x62, 0x63}

这里a,b,c的ASCII分别是0x61, 0x62, 0x63

8.4字节转换字符串#

直接使用string转换即可

package main
import (
    "fmt"
)
func main(){
    var bytes []byte = []byte{'a','b','c'}
    fmt.Printf("%T,%#v\n",bytes,bytes)

    sb := string(bytes)
    fmt.Printf("%T %v\n",sb,sb)
}

将定义的bytes转换成字符串

[root@www.linuxea.com /opt/Golang/work2]# go run byte.go 
[]uint8,[]byte{0x61, 0x62, 0x63}
string abc

8.5字符串转字节#

将转换过的字符串再转回字节

package main
import (
    "fmt"
)
func main(){
    var bytes []byte = []byte{'a','b','c'}
    fmt.Printf("%T,%#v\n",bytes,bytes)

    sb := string(bytes)
    fmt.Printf("%T %v\n",sb,sb)


    bs := []byte(sb)
    fmt.Printf("%T %#v\n",bs,bs)
}

如下

[root@www.linuxea.com /opt/Golang/work2]# go run byte.go 
[]uint8,[]byte{0x61, 0x62, 0x63}
string abc
[]uint8 []byte{0x61, 0x62, 0x63}

8.6bytes包#

bytes包与strings包基本上一样

按照直接数组进行比较

fmt.Println(bytes.Compare([]byte("abc"),[]byte("def")))

运行

[root@www.linuxea.com /opt/Golang/work2]# go run byte.go
-1

bytes.Index索引位置

计算字节def在abcdef的索引位置

fmt.Println(bytes.Index([]byte("abcdef"),[]byte("def")))

运行

[root@www.linuxea.com /opt/Golang/work2]# go run byte.go
3

字节abcdef是否包含def,如果包含则为true,否则false

fmt.Println(bytes.Contains([]byte("abcdef"),[]byte("def")))

运行

[root@www.linuxea.com /opt/Golang/work2]# go run byte.go
true

8.7计算unicode#

当使用len计算字符串是可以的,但是遇到中文字符就需要unicode/utf8模块计算。如下:

[root@www.linuxea.com /opt/Golang/work2]# cat byte1.go
package main
import (
    "fmt"
    "unicode/utf8"
)
func main(){
    s := "这是一个测试"
    fmt.Println(s)
    fmt.Println(utf8.RuneCountInString(s))
}

运行

[root@www.linuxea.com /opt/Golang/work2]# go run byte1.go
这是一个测试
6

9.字符串与其他类型的转换#

转换bool,int

9.1字符串转换Bool类型#

如下:

strconv.ParseBool("true")

会返回两个值,其中一个是err,接收两个值,如果err等于nil,说明没有错误,就打印v,如果有错误,就打印。如下:

[root@www.linuxea.com /opt/Golang/work2]# cat strcov.go
package main
import (
    "fmt"
    "strconv"
)
func main(){
    if v,err := strconv.ParseBool("true");err == nil {
        fmt.Println(v)
    } else {
        fmt.Println(err)
    }
}

运行

[root@www.linuxea.com /opt/Golang/work2]# go run strcov.go
true

9.2字符串转换int类型#

如下:

strconv.Atoi("1024")

会返回两个值,其中一个是err,接收两个值,如果err等于nil,说明没有错误,就打印v,如果有错误,就打印。如下:

[root@www.linuxea.com /opt/Golang/work2]# cat strcov.go
package main
import (
    "fmt"
    "strconv"
)
func main(){

    if v,err := strconv.Atoi("1024");err == nil{
        fmt.Println(v)
    }else{
        fmt.Println(err)
    }
}

运行

[root@www.linuxea.com /opt/Golang/work2]# go run atoi.go
1024

另外,使用strconv.ParseInt()也可以转换成int类型,但是需要指定转换的字节

    if v,err := strconv.ParseInt("64",16,64);err == nil {
        fmt.Println(v)
    }else{
        fmt.Println(err)
    }
[root@www.linuxea.com /opt/Golang/work2]# go run atoi.go
100

16*6+4=100

9.3字符串转换float#

如下:

strconv.ParseFloat("1.024",64)

会返回两个值,其中一个是err,接收两个值,如果err等于nil,说明没有错误,就打印v,如果有错误,就打印。如下:

package main
import (
    "fmt"
    "strconv"
)
func main(){

    if v,err := strconv.ParseFloat("1.024",64);err == nil{
        fmt.Println(v)
        fmt.Printf("%T",v)
    }else{
        fmt.Println(err)
    }
}

10.其他类型转换字符串#

Sprintf可以将其他类型转换成字符串

10.1将int转换字符串#

Sprintf转换int到字符串,%d

fmt.Sprintf("%d",12)

代码块

package main
import (
    "fmt"
)
func main(){
    a := fmt.Sprintf("%d",12)
    fmt.Println(a)
    fmt.Printf("%T",a)
}

运行

[root@www.linuxea.com /opt/Golang/work2]# go run fmt.go
12
string

10.2float浮点数转换为字符串#

Sprintf转换float到字符串,%f

fmt.Sprintf("%f",12.2)

代码块

package main
import (
    "fmt"
)
func main(){
    a := fmt.Sprintf("%f",12.2)
    fmt.Println(a)
    fmt.Printf("%T",a)
}

运行

[root@www.linuxea.com /opt/Golang/work2]# go run fmt2.go
12.200000
string

10.3FormatBool布尔转换字符串#

将bool转换字符串

strconv.FormatBool(false)

代码块

package main
import (
    "fmt"
    "strconv"
)
func main(){
    a := strconv.FormatBool(false)
    fmt.Printf("%T,%v",a,a)
}

运行

[root@www.linuxea.com /opt/Golang/work2]# go run fmt3.go
string,false

10.4 Itoa将int类型转换为字符串#

将int类型转换为字符串

 strconv.Itoa(123)

代码块

package main
import (
    "fmt"
    "strconv"
)
func main(){
    a := strconv.Itoa(123)
    fmt.Printf("%T,%v",a,a)
}

运行

[root@www.linuxea.com /opt/Golang/work2]# go run fmt4.go
string,123

10.5 FormatInt进制类型转换字符串#

123转换10进制

strconv.FormatInt(123,10)

代码块

package main
import (
    "fmt"
    "strconv"
)
func main(){
    a := strconv.FormatInt(123,10)
    fmt.Printf("%T,%v",a,a)
}

运行

[root@www.linuxea.com /opt/Golang/work2]# go run fmt5.go 
string,123
package main
import (
    "fmt"
    "strconv"
)
func main(){
    a := strconv.FormatInt(123,16)
    fmt.Printf("%T,%v",a,a)
}
[root@www.linuxea.com /opt/Golang/work2]# go run fmt5.go 
string,7b
package main
import (
    "fmt"
    "strconv"
)
func main(){
    a := strconv.FormatInt(123,8)
    fmt.Printf("%T,%v",a,a)
}
[root@www.linuxea.com /opt/Golang/work2]# go run fmt5.go
string,173

10.6 FormatFloat转换字符串#

指定一个十进制或者科学记数法,‘E’是科学计数法,如果是转换10进制这里写'f',-1精度,64是float64类型

strconv.FormatFloat(10.11,'E',-1,64)

代码块

package main
import (
    "fmt"
    "strconv"
)
func main(){
    a := strconv.FormatFloat(10.11,'E',-1,64)
    fmt.Printf("%T,%v",a,a)
}

运行

[root@www.linuxea.com /opt/Golang/work2]# go run fmt5.go
string,1.011E+01

练习题1#

把数据最大的排序到最后

eights := []int{10,2,30,15,9,5} 

先把最大的数字放在最后

从第一个开始,两个进行比较,如果前面的高,就交换位置

10,2比较,交换位置,就成了2,10,30,15,9,5

10,30比较,不交换位置,就成了2,10,30,15,9,5

30,15比较,交换位置,就成了2,10,15,30,9,5

30,9比较,交换位置,就成了2,10,15,9,30,5

30,5比较,交换位置,就成了2,10,15,9,5,30

n个比较,n-1

如果前面的高就进行交换heights[i] > heights[i+1],而后进行角色交换

借助一个中间变量进行交换,定义一个tmp,tmp := heights[i]

heights[i],heights[i] = heights[i+1]

而后heights[i+1] = tmp

或者直接

heights[i],heights[i+1] = heights[i+1],heights[i]

用第一种,如下:

package main
import (
    "fmt"
)
func main(){
    heights := []int{10,2,30,15,9,5}
    for i :=0; i < len(heights)-1; i++ {
        if heights[i] > heights[i+1] {
            fmt.Println("交换:",heights[i],heights[i+1])
            tmp := heights[i]
            heights[i] = heights[i+1]
            heights[i+1] = tmp
        }
        fmt.Println(i,"交换完成:",heights)
    }
}

运行

[root@www.linuxea.com /opt/Golang/work2]# go run work4.go
交换: 10 2
0 交换完成: [2 10 30 15 9 5]
1 交换完成: [2 10 30 15 9 5]
交换: 30 15
2 交换完成: [2 10 15 30 9 5]
交换: 30 9
3 交换完成: [2 10 15 9 30 5]
交换: 30 5
4 交换完成: [2 10 15 9 5 30]

把数据最大的排序到最后,倒叙排列。加一层for循环

for j := 0; j<len(heights)-1; j++{
    fmt.Println("第",j,"轮")
    for i :=0; i < len(heights)-1; i++ {
        if heights[i] > heights[i+1] {
            fmt.Println("交换:",heights[i],heights[i+1])
            tmp := heights[i]
            heights[i] = heights[i+1]
            heights[i+1] = tmp
        }
        fmt.Println(i,"交换完成:",heights)
    }
    fmt.Println("第",j,"轮,结果",heights)
}

代码块

package main
import (
    "fmt"
)
func main(){
    heights := []int{10,2,30,15,9,5}

for j := 0; j<len(heights)-1; j++{
    fmt.Println("第",j,"轮")
    for i :=0; i < len(heights)-1; i++ {
        if heights[i] > heights[i+1] {
            fmt.Println("交换:",heights[i],heights[i+1])
            tmp := heights[i]
            heights[i] = heights[i+1]
            heights[i+1] = tmp
        }
        fmt.Println(i,"交换完成:",heights)
    }
    fmt.Println("第",j,"轮,结果",heights)
    }
}

运行

[root@www.linuxea.com /opt/Golang/work2]# go run work4.go
第 0 轮
交换: 10 2
0 交换完成: [2 10 30 15 9 5]
1 交换完成: [2 10 30 15 9 5]
交换: 30 15
2 交换完成: [2 10 15 30 9 5]
交换: 30 9
3 交换完成: [2 10 15 9 30 5]
交换: 30 5
4 交换完成: [2 10 15 9 5 30]
第 0 轮,结果 [2 10 15 9 5 30]
第 1 轮
0 交换完成: [2 10 15 9 5 30]
1 交换完成: [2 10 15 9 5 30]
交换: 15 9
2 交换完成: [2 10 9 15 5 30]
交换: 15 5
3 交换完成: [2 10 9 5 15 30]
4 交换完成: [2 10 9 5 15 30]
第 1 轮,结果 [2 10 9 5 15 30]
第 2 轮
0 交换完成: [2 10 9 5 15 30]
交换: 10 9
1 交换完成: [2 9 10 5 15 30]
交换: 10 5
2 交换完成: [2 9 5 10 15 30]
3 交换完成: [2 9 5 10 15 30]
4 交换完成: [2 9 5 10 15 30]
第 2 轮,结果 [2 9 5 10 15 30]
第 3 轮
0 交换完成: [2 9 5 10 15 30]
交换: 9 5
1 交换完成: [2 5 9 10 15 30]
2 交换完成: [2 5 9 10 15 30]
3 交换完成: [2 5 9 10 15 30]
4 交换完成: [2 5 9 10 15 30]
第 3 轮,结果 [2 5 9 10 15 30]
第 4 轮
0 交换完成: [2 5 9 10 15 30]
1 交换完成: [2 5 9 10 15 30]
2 交换完成: [2 5 9 10 15 30]
3 交换完成: [2 5 9 10 15 30]
4 交换完成: [2 5 9 10 15 30]
第 4 轮,结果 [2 5 9 10 15 30]

如果只是要获取最大值则可以如下:

如: 获取[]int{1,3,3,5,76,87,20,10}最大值

package main
import (
    "fmt"
)
func main(){
    nums := []int{1,3,3,5,76,87,20,10}
    maxNum := nums[0]

    for i,v := range nums {
        if v > maxNum {
            maxNum =v 
        }
    }
    fmt.Println(i,"=",maxNum)
}

运行

[root@www.linuxea.com /opt/Golang/work2]# go run work5.go
0 = 1
1 = 3
2 = 3
3 = 5
4 = 76
5 = 87
6 = 87
7 = 87
87

练习题2#

计算第一个最大值和第二个最大值

写两个变量,进行比较

maxNum,secondNum := nums[0],nums[0]

遍历nums,如果v大于maxNum的时候,maxNum就存放在secondNum上,maxNum也被v替换成,在比较是不是比secondNum,如果大于v就替换secondNum

如果v等于maxNum,说明有两个最大值,跳过即可。if v == maxNum

package main
import (
    "fmt"
)
func main(){
    nums := []int{1,3,3,5,76,87,20,10}
    maxNum,secondNum := nums[0],nums[0]

    for i,v := range nums {
        if v > maxNum {
            secondNum = maxNum
            maxNum = v 
        }else if v == maxNum{
            continue
        }else if v > secondNum {
            secondNum = v 
        }
    fmt.Println(i,"=",maxNum,secondNum)
    }
    fmt.Println(maxNum,secondNum)
}

运行

[root@www.linuxea.com /opt/Golang/work2]# go run work5.go
0 = 1 1
1 = 3 1
2 = 3 3
3 = 5 3
4 = 76 5
5 = 87 76
6 = 87 76
7 = 87 76
87 76

练习题3#

取映射中所有key组成的切片,获取映射中所有value组成的切片。如下:

users := map[string]int{"mark":10,"sean":9,"justin":2,"edwin":6}

使用for循环遍历,屏蔽掉k或者v来解决,如下

[root@www.linuxea.com /opt/Golang/work2]# cat work8.go
package main
import (
    "fmt"
)
func main(){
    users := map[string]int{"mark":10,"sean":9,"justin":2,"edwin":6}

    for k := range users{
        fmt.Println("k:",k)
    }

    for _,v := range users{
        fmt.Println("v:",v)
    }


}

运行

[root@www.linuxea.com /opt/Golang/work2]# go run work8.go
k: mark
k: sean
k: justin
k: edwin
v: 2
v: 6
v: 10
v: 9

分别定义两个切片来解决。如下:

values := []int{}
keys := make([]string,len(users))

values,keys分别将存放users中的数字和字符串。keys中的len(users)在第一次就会被定义好。而后使用append写到定义好的两个切片中。

进行遍历并追加到两个定义的切片中

    for k,v := range users{
        values = append(values,v)
        keys = append(keys,k)
        fmt.Println(k,v)
    }

代码块

package main
import (
    "fmt"
)
func main(){
    users := map[string]int{"mark":10,"sean":9,"justin":2,"edwin":6}

    values := []int{}
    keys := make([]string,len(users))

    for k,v := range users{
        values = append(values,v)
        keys = append(keys,k)
        fmt.Println(k,v)
    }
    fmt.Println(values,keys)
}

运行

[root@www.linuxea.com /opt/Golang/work2]# go run work6.go
justin 2
edwin 6
mark 10
sean 9
[2 6 10 9] [    justin edwin mark sean]

仍然使用上面定义的代码,我们修改下:

定义一个i变量等于0,然后遍历的时候,将key赋值给i,而后i++,如下:

    values := []int{}
    keys := make([]string,len(users))

    i := 0
    for k,v := range users{
        values = append(values,v)
        keys[i] = k
        i++
        fmt.Println(k,v)
    }

运行

[root@www.linuxea.com /opt/Golang/work2]# go run work7.go
mark 10
sean 9
justin 2
edwin 6
[10 9 2 6] [mark sean justin edwin]

练习题4#

此前计算了一个每个字符串出现的次数,在进行计算出现次数的英文列表。此前的代码如下:

package main
import "fmt"
func main(){

   article := `Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additionsto that Work or Derivative Works thereof, that is intentionallysubmitted to Licensor for inclusion in the Work by the copyright owneror by an individual or Legal Entity authorized to submit on behalf ofthe copyright owner. For the purposes of this definition, "submitted"means any form of electronic, verbal, or written communication sentto the Licensor or its representatives, including but not limited tocommunication on electronic mailing lists, source code control systems,and issue tracking systems that are managed by, or on behalf of, theLicensor for the purpose of discussing and improving the Work, butexcluding communication that is conspicuously marked or otherwisedesignated in writing by the copyright owner as "Not a Contribution.""Contributor" shall mean Licensor and any individual or Legal Entityon behalf of whom a Contribution has been received by Licensor andsubsequently incorporated within the Work.2. Grant of Copyright License. Subject to the terms and conditions ofthis License, each Contributor hereby grants to You a perpetual,worldwide, non-exclusive, no-charge, royalty-free, irrevocablecopyright license to reproduce, prepare Derivative Works of,publicly display, publicly perform, sublicense, and distribute theWork and such Derivative Works in Source or Object form.Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual,worldwide, non-exclusive, no-charge, royalty-free, irrevocable(except as stated in this section) patent license to make, have made,use, offer to sell, sell, import, and otherwise transfer the Work,where such license applies only to those patent claims licensableby such Contributor that are necessarily infringed by theirContribution(s) alone or by combination of their Contribution(s)with the Work to which such Contribution(s) was submitted. If Youinstitute patent litigation against any entity (including across-claim or counterclaim in a lawsuit) alleging that the Workor a Contribution incorporated within the Work constitutes director contributory patent infringement, then any patent licensesgranted to You under this License for that Work shall terminateas of the date such litigation is filed.`

    article_stat := map[rune]int{}

    for _,ch := range article {
        if ch >= 'A' && ch <= 'Z' || ch >= 'a' && ch <= 'z' {
            article_stat[ch]++
        }
    }
    fmt.Println(article_stat)
    for ch,cnt := range article_stat {
        fmt.Printf("%c:%d\n",ch,cnt)
    }
}

预期想得到,比如:

出现10次的a,g,c 
出现16次的w,l,s
出现36次的m,o,p

这样就需要定义一个countStats,key是int类型,value是切片类型 []rune,对于映射来讲需要初始化,需要加上{},[]rune{}

countStats := map[int][]rune{}

[]rune{} 为nil切片,可以进行append

上个作业中article_stat已经有了字符出现的次数,现在只需要进行遍历.

是article_stat中的数值是这样的 c:81 W:14 E:2 F:1

如果int数值在map中,就append,如果不在就初始化一个空的映射,开始遍历

for k,v := range article_stat {

而后进行判断值是不是在countStats中,这里遍历后是v。如果在就append,不在就初始化空值。

    if _,ok := countStats[v];ok{
        countStats[v] = append(countStats[v],k)
    } else {
        countStats[v] = []rune{k}
    }

而后进行打印

    fmt.Println(countStats)

代码块如下:

package main
import "fmt"
func main(){

   article := `Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additionsto that Work or Derivative Works thereof, that is intentionallysubmitted to Licensor for inclusion in the Work by the copyright owneror by an individual or Legal Entity authorized to submit on behalf ofthe copyright owner. For the purposes of this definition, "submitted"means any form of electronic, verbal, or written communication sentto the Licensor or its representatives, including but not limited tocommunication on electronic mailing lists, source code control systems,and issue tracking systems that are managed by, or on behalf of, theLicensor for the purpose of discussing and improving the Work, butexcluding communication that is conspicuously marked or otherwisedesignated in writing by the copyright owner as "Not a Contribution.""Contributor" shall mean Licensor and any individual or Legal Entityon behalf of whom a Contribution has been received by Licensor andsubsequently incorporated within the Work.2. Grant of Copyright License. Subject to the terms and conditions ofthis License, each Contributor hereby grants to You a perpetual,worldwide, non-exclusive, no-charge, royalty-free, irrevocablecopyright license to reproduce, prepare Derivative Works of,publicly display, publicly perform, sublicense, and distribute theWork and such Derivative Works in Source or Object form.Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual,worldwide, non-exclusive, no-charge, royalty-free, irrevocable(except as stated in this section) patent license to make, have made,use, offer to sell, sell, import, and otherwise transfer the Work,where such license applies only to those patent claims licensableby such Contributor that are necessarily infringed by theirContribution(s) alone or by combination of their Contribution(s)with the Work to which such Contribution(s) was submitted. If Youinstitute patent litigation against any entity (including across-claim or counterclaim in a lawsuit) alleging that the Workor a Contribution incorporated within the Work constitutes director contributory patent infringement, then any patent licensesgranted to You under this License for that Work shall terminateas of the date such litigation is filed.`

    article_stat := map[rune]int{}

    for _,ch := range article {
        if ch >= 'A' && ch <= 'Z' || ch >= 'a' && ch <= 'z' {
            article_stat[ch]++
        }
    }
    //fmt.Println(article_stat)
    //for ch,cnt := range article_stat {
    //  fmt.Printf("%c:%d\n",ch,cnt)
    //}



    countStats := map[int][]rune{}
    for k,v := range article_stat {
        if _,ok := countStats[v];ok{
            countStats[v] = append(countStats[v],k)
        } else {
            countStats[v] = []rune{k}
        }
    fmt.Println(countStats)
    }
}

运行

[root@DT_Node-172_17_0_1 /opt/Golang/work2]# go run work10.go
map[39:[121]]
map[18:[107] 39:[121]]
map[2:[69] 18:[107] 39:[121]]
map[1:[70] 2:[69] 18:[107] 39:[121]]
map[1:[70] 2:[69] 3:[83] 18:[107] 39:[121]]
map[1:[70] 2:[69] 3:[83] 18:[107] 39:[121] 66:[117]]
map[1:[70] 2:[69] 3:[83] 18:[107] 39:[121] 66:[117] 69:[108]]
map[1:[70] 2:[69] 3:[83] 18:[107] 36:[109] 39:[121] 66:[117] 69:[108]]
map[1:[70 80] 2:[69] 3:[83] 18:[107] 36:[109] 39:[121] 66:[117] 69:[108]]
map[1:[70 80 73] 2:[69] 3:[83] 18:[107] 36:[109] 39:[121] 66:[117] 69:[108]]
map[1:[70 80 73] 2:[69] 3:[83] 4:[89] 18:[107] 36:[109] 39:[121] 66:[117] 69:[108]]
map[1:[70 80 73] 2:[69] 3:[83] 4:[89] 12:[67] 18:[107] 36:[109] 39:[121] 66:[117] 69:[108]]
map[1:[70 80 73] 2:[69] 3:[83] 4:[89] 12:[67] 18:[107] 20:[119] 36:[109] 39:[121] 66:[117] 69:[108]]
map[1:[70 80 73] 2:[69 71] 3:[83] 4:[89] 12:[67] 18:[107] 20:[119] 36:[109] 39:[121] 66:[117] 69:[108]]
map[1:[70 80 73] 2:[69 71] 3:[83] 4:[89] 12:[67] 18:[107] 20:[119] 36:[109 102] 39:[121] 66:[117] 69:[108]]
map[1:[70 80 73] 2:[69 71] 3:[83] 4:[89] 12:[67] 18:[107] 20:[119] 35:[112] 36:[109 102] 39:[121] 66:[117] 69:[108]]
map[1:[70 80 73 78] 2:[69 71] 3:[83] 4:[89] 12:[67] 18:[107] 20:[119] 35:[112] 36:[109 102] 39:[121] 66:[117] 69:[108]]
map[1:[70 80 73 78] 2:[69 71] 3:[83] 4:[89 120] 12:[67] 18:[107] 20:[119] 35:[112] 36:[109 102] 39:[121] 66:[117] 69:[108]]
map[1:[70 80 73 78] 2:[69 71] 3:[83] 4:[89 120] 12:[67] 18:[107] 20:[119] 35:[112] 36:[109 102] 39:[121] 66:[117] 69:[108] 160:[110]]
map[1:[70 80 73 78] 2:[69 71] 3:[83] 4:[89 120] 12:[67] 18:[107] 20:[119] 35:[112] 36:[109 102] 39:[121] 45:[98] 66:[117] 69:[108] 160:[110]]
map[1:[70 80 73 78] 2:[69 71] 3:[83 68] 4:[89 120] 12:[67] 18:[107] 20:[119] 35:[112] 36:[109 102] 39:[121] 45:[98] 66:[117] 69:[108] 160:[110]]
map[1:[70 80 73 78 122] 2:[69 71] 3:[83 68] 4:[89 120] 12:[67] 18:[107] 20:[119] 35:[112] 36:[109 102] 39:[121] 45:[98] 66:[117] 69:[108] 160:[110]]
map[1:[70 80 73 78 122] 2:[69 71] 3:[83 68 106] 4:[89 120] 12:[67] 18:[107] 20:[119] 35:[112] 36:[109 102] 39:[121] 45:[98] 66:[117] 69:[108] 160:[110]]
map[1:[70 80 73 78 122] 2:[69 71] 3:[83 68 106] 4:[89 120] 12:[67] 18:[107] 20:[119] 35:[112] 36:[109 102] 39:[121] 45:[98] 66:[117] 69:[108] 117:[97] 160:[110]]
map[1:[70 80 73 78 122] 2:[69 71] 3:[83 68 106] 4:[89 120] 12:[67] 18:[107] 20:[119] 35:[112] 36:[109 102] 39:[121] 45:[98] 66:[117] 69:[108] 81:[99] 117:[97] 160:[110]]
map[1:[70 80 73 78 122] 2:[69 71] 3:[83 68 106] 4:[89 120] 12:[67 76] 18:[107] 20:[119] 35:[112] 36:[109 102] 39:[121] 45:[98] 66:[117] 69:[108] 81:[99] 117:[97] 160:[110]]
map[1:[70 80 73 78 122] 2:[69 71] 3:[83 68 106] 4:[89 120] 12:[67 76] 14:[87] 18:[107] 20:[119] 35:[112] 36:[109 102] 39:[121] 45:[98] 66:[117] 69:[108] 81:[99] 117:[97] 160:[110]]
map[1:[70 80 73 78 122] 2:[69 71] 3:[83 68 106] 4:[89 120] 12:[67 76] 14:[87] 18:[107] 20:[119] 35:[112] 36:[109 102] 39:[121] 45:[98] 66:[117] 69:[108] 73:[104] 81:[99] 117:[97] 160:[110]]
map[1:[70 80 73 78 122] 2:[69 71] 3:[83 68 106] 4:[89 120] 12:[67 76] 14:[87] 18:[107] 20:[119] 35:[112] 36:[109 102] 39:[121] 45:[98] 66:[117] 69:[108] 73:[104] 81:[99] 117:[97] 160:[110] 193:[101]]
map[1:[70 80 73 78 122] 2:[69 71] 3:[83 68 106] 4:[89 120] 12:[67 76] 14:[87] 18:[107 118] 20:[119] 35:[112] 36:[109 102] 39:[121] 45:[98] 66:[117] 69:[108] 73:[104] 81:[99] 117:[97] 160:[110] 193:[101]]
map[1:[70 80 73 78 122 113] 2:[69 71] 3:[83 68 106] 4:[89 120] 12:[67 76] 14:[87] 18:[107 118] 20:[119] 35:[112] 36:[109 102] 39:[121] 45:[98] 66:[117] 69:[108] 73:[104] 81:[99] 117:[97] 160:[110] 193:[101]]
map[1:[70 80 73 78 122 113 79] 2:[69 71] 3:[83 68 106] 4:[89 120] 12:[67 76] 14:[87] 18:[107 118] 20:[119] 35:[112] 36:[109 102] 39:[121] 45:[98] 66:[117] 69:[108] 73:[104] 81:[99] 117:[97] 160:[110] 193:[101]]
map[1:[70 80 73 78 122 113 79] 2:[69 71] 3:[83 68 106] 4:[89 120] 12:[67 76] 14:[87] 18:[107 118] 20:[119] 35:[112] 36:[109 102] 39:[121] 45:[98] 66:[117] 69:[108] 73:[104] 81:[99] 117:[97] 160:[110] 177:[111] 193:[101]]
map[1:[70 80 73 78 122 113 79] 2:[69 71] 3:[83 68 106] 4:[89 120] 12:[67 76] 14:[87] 18:[107 118] 20:[119] 35:[112] 36:[109 102] 39:[121] 45:[98] 66:[117] 69:[108] 73:[104] 81:[99] 117:[97] 160:[110] 177:[111] 193:[101] 197:[116]]
map[1:[70 80 73 78 122 113 79] 2:[69 71] 3:[83 68 106] 4:[89 120] 12:[67 76] 14:[87] 18:[107 118] 20:[119] 35:[112] 36:[109 102] 39:[121] 45:[98] 66:[117] 69:[108] 73:[104] 81:[99] 117:[97] 142:[114] 160:[110] 177:[111] 193:[101] 197:[116]]
map[1:[70 80 73 78 122 113 79] 2:[69 71] 3:[83 68 106] 4:[89 120] 12:[67 76] 14:[87] 18:[107 118] 20:[119] 31:[103] 35:[112] 36:[109 102] 39:[121] 45:[98] 66:[117] 69:[108] 73:[104] 81:[99] 117:[97] 142:[114] 160:[110] 177:[111] 193:[101] 197:[116]]
map[1:[70 80 73 78 122 113 79] 2:[69 71] 3:[83 68 106] 4:[89 120] 12:[67 76] 14:[87] 18:[107 118] 20:[119] 31:[103] 35:[112] 36:[109 102] 39:[121] 45:[98] 66:[117] 69:[108] 73:[104] 81:[99] 117:[97] 142:[114] 160:[110] 177:[111] 178:[105] 193:[101] 197:[116]]
map[1:[70 80 73 78 122 113 79] 2:[69 71] 3:[83 68 106] 4:[89 120] 12:[67 76] 14:[87] 18:[107 118] 20:[119] 31:[103] 35:[112] 36:[109 102] 39:[121] 45:[98] 66:[117] 69:[108] 73:[104] 81:[99] 111:[115] 117:[97] 142:[114] 160:[110] 177:[111] 178:[105] 193:[101] 197:[116]]
map[1:[70 80 73 78 122 113 79] 2:[69 71] 3:[83 68 106] 4:[89 120] 12:[67 76] 14:[87] 18:[107 118] 20:[119] 31:[103] 35:[112] 36:[109 102] 39:[121] 45:[98] 53:[100] 66:[117] 69:[108] 73:[104] 81:[99] 111:[115] 117:[97] 142:[114] 160:[110] 177:[111] 178:[105] 193:[101] 197:[116]]

这里的切片是nil, 也就是可以进行append的。映射在key不存在的时候返回是一个值类型的零值

由此,将if语句改成一条

    countStats[v] = append(countStats[v],k)

那么这里的代码就变成如下:

package main
import "fmt"
func main(){

   article := `Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additionsto that Work or Derivative Works thereof, that is intentionallysubmitted to Licensor for inclusion in the Work by the copyright owneror by an individual or Legal Entity authorized to submit on behalf ofthe copyright owner. For the purposes of this definition, "submitted"means any form of electronic, verbal, or written communication sentto the Licensor or its representatives, including but not limited tocommunication on electronic mailing lists, source code control systems,and issue tracking systems that are managed by, or on behalf of, theLicensor for the purpose of discussing and improving the Work, butexcluding communication that is conspicuously marked or otherwisedesignated in writing by the copyright owner as "Not a Contribution.""Contributor" shall mean Licensor and any individual or Legal Entityon behalf of whom a Contribution has been received by Licensor andsubsequently incorporated within the Work.2. Grant of Copyright License. Subject to the terms and conditions ofthis License, each Contributor hereby grants to You a perpetual,worldwide, non-exclusive, no-charge, royalty-free, irrevocablecopyright license to reproduce, prepare Derivative Works of,publicly display, publicly perform, sublicense, and distribute theWork and such Derivative Works in Source or Object form.Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual,worldwide, non-exclusive, no-charge, royalty-free, irrevocable(except as stated in this section) patent license to make, have made,use, offer to sell, sell, import, and otherwise transfer the Work,where such license applies only to those patent claims licensableby such Contributor that are necessarily infringed by theirContribution(s) alone or by combination of their Contribution(s)with the Work to which such Contribution(s) was submitted. If Youinstitute patent litigation against any entity (including across-claim or counterclaim in a lawsuit) alleging that the Workor a Contribution incorporated within the Work constitutes director contributory patent infringement, then any patent licensesgranted to You under this License for that Work shall terminateas of the date such litigation is filed.`

    article_stat := map[rune]int{}

    for _,ch := range article {
        if ch >= 'A' && ch <= 'Z' || ch >= 'a' && ch <= 'z' {
            article_stat[ch]++
        }
    }
//  fmt.Println(article_stat)
//  for ch,cnt := range article_stat {
//      fmt.Printf("%c:%d\n",ch,cnt)
//  }

    countStats := map[int][]rune{}
    for k,v := range article_stat {
        countStats[v] = append(countStats[v],k)
    fmt.Println(countStats)
    }
}

运行

[root@DT_Node-172_17_0_1 /opt/Golang/work2]# go run work10.go
map[69:[108]]
map[53:[100] 69:[108]]
map[3:[68] 53:[100] 69:[108]]
map[3:[68] 4:[120] 53:[100] 69:[108]]
map[3:[68 83] 4:[120] 53:[100] 69:[108]]
map[3:[68 83 106] 4:[120] 53:[100] 69:[108]]
map[3:[68 83 106] 4:[120] 45:[98] 53:[100] 69:[108]]
map[3:[68 83 106] 4:[120] 36:[102] 45:[98] 53:[100] 69:[108]]
map[3:[68 83 106] 4:[120] 36:[102] 45:[98] 53:[100] 69:[108] 81:[99]]
map[3:[68 83 106] 4:[120] 31:[103] 36:[102] 45:[98] 53:[100] 69:[108] 81:[99]]
map[3:[68 83 106] 4:[120] 14:[87] 31:[103] 36:[102] 45:[98] 53:[100] 69:[108] 81:[99]]
map[3:[68 83 106] 4:[120] 12:[67] 14:[87] 31:[103] 36:[102] 45:[98] 53:[100] 69:[108] 81:[99]]
map[3:[68 83 106] 4:[120] 12:[67] 14:[87] 31:[103] 36:[102] 45:[98] 53:[100] 69:[108] 81:[99] 142:[114]]
map[3:[68 83 106] 4:[120] 12:[67] 14:[87] 31:[103] 36:[102] 45:[98] 53:[100] 69:[108] 81:[99] 142:[114] 178:[105]]
map[1:[70] 3:[68 83 106] 4:[120] 12:[67] 14:[87] 31:[103] 36:[102] 45:[98] 53:[100] 69:[108] 81:[99] 142:[114] 178:[105]]
map[1:[70 78] 3:[68 83 106] 4:[120] 12:[67] 14:[87] 31:[103] 36:[102] 45:[98] 53:[100] 69:[108] 81:[99] 142:[114] 178:[105]]
map[1:[70 78] 3:[68 83 106] 4:[120 89] 12:[67] 14:[87] 31:[103] 36:[102] 45:[98] 53:[100] 69:[108] 81:[99] 142:[114] 178:[105]]
map[1:[70 78 80] 3:[68 83 106] 4:[120 89] 12:[67] 14:[87] 31:[103] 36:[102] 45:[98] 53:[100] 69:[108] 81:[99] 142:[114] 178:[105]]
map[1:[70 78 80] 3:[68 83 106] 4:[120 89] 12:[67] 14:[87] 31:[103] 36:[102] 45:[98] 53:[100] 69:[108] 81:[99] 142:[114] 177:[111] 178:[105]]
map[1:[70 78 80] 3:[68 83 106] 4:[120 89] 12:[67] 14:[87] 31:[103] 36:[102] 39:[121] 45:[98] 53:[100] 69:[108] 81:[99] 142:[114] 177:[111] 178:[105]]
map[1:[70 78 80 113] 3:[68 83 106] 4:[120 89] 12:[67] 14:[87] 31:[103] 36:[102] 39:[121] 45:[98] 53:[100] 69:[108] 81:[99] 142:[114] 177:[111] 178:[105]]
map[1:[70 78 80 113 73] 3:[68 83 106] 4:[120 89] 12:[67] 14:[87] 31:[103] 36:[102] 39:[121] 45:[98] 53:[100] 69:[108] 81:[99] 142:[114] 177:[111] 178:[105]]
map[1:[70 78 80 113 73] 3:[68 83 106] 4:[120 89] 12:[67] 14:[87] 31:[103] 36:[102] 39:[121] 45:[98] 53:[100] 69:[108] 81:[99] 142:[114] 160:[110] 177:[111] 178:[105]]
map[1:[70 78 80 113 73] 3:[68 83 106] 4:[120 89] 12:[67] 14:[87] 31:[103] 36:[102] 39:[121] 45:[98] 53:[100] 69:[108] 81:[99] 117:[97] 142:[114] 160:[110] 177:[111] 178:[105]]
map[1:[70 78 80 113 73] 3:[68 83 106] 4:[120 89] 12:[67] 14:[87] 20:[119] 31:[103] 36:[102] 39:[121] 45:[98] 53:[100] 69:[108] 81:[99] 117:[97] 142:[114] 160:[110] 177:[111] 178:[105]]
map[1:[70 78 80 113 73] 3:[68 83 106] 4:[120 89] 12:[67] 14:[87] 18:[118] 20:[119] 31:[103] 36:[102] 39:[121] 45:[98] 53:[100] 69:[108] 81:[99] 117:[97] 142:[114] 160:[110] 177:[111] 178:[105]]
map[1:[70 78 80 113 73] 3:[68 83 106] 4:[120 89] 12:[67 76] 14:[87] 18:[118] 20:[119] 31:[103] 36:[102] 39:[121] 45:[98] 53:[100] 69:[108] 81:[99] 117:[97] 142:[114] 160:[110] 177:[111] 178:[105]]
map[1:[70 78 80 113 73 79] 3:[68 83 106] 4:[120 89] 12:[67 76] 14:[87] 18:[118] 20:[119] 31:[103] 36:[102] 39:[121] 45:[98] 53:[100] 69:[108] 81:[99] 117:[97] 142:[114] 160:[110] 177:[111] 178:[105]]
map[1:[70 78 80 113 73 79] 3:[68 83 106] 4:[120 89] 12:[67 76] 14:[87] 18:[118] 20:[119] 31:[103] 36:[102] 39:[121] 45:[98] 53:[100] 66:[117] 69:[108] 81:[99] 117:[97] 142:[114] 160:[110] 177:[111] 178:[105]]
map[1:[70 78 80 113 73 79] 2:[69] 3:[68 83 106] 4:[120 89] 12:[67 76] 14:[87] 18:[118] 20:[119] 31:[103] 36:[102] 39:[121] 45:[98] 53:[100] 66:[117] 69:[108] 81:[99] 117:[97] 142:[114] 160:[110] 177:[111] 178:[105]]
map[1:[70 78 80 113 73 79] 2:[69] 3:[68 83 106] 4:[120 89] 12:[67 76] 14:[87] 18:[118] 20:[119] 31:[103] 36:[102 109] 39:[121] 45:[98] 53:[100] 66:[117] 69:[108] 81:[99] 117:[97] 142:[114] 160:[110] 177:[111] 178:[105]]
map[1:[70 78 80 113 73 79] 2:[69] 3:[68 83 106] 4:[120 89] 12:[67 76] 14:[87] 18:[118] 20:[119] 31:[103] 36:[102 109] 39:[121] 45:[98] 53:[100] 66:[117] 69:[108] 73:[104] 81:[99] 117:[97] 142:[114] 160:[110] 177:[111] 178:[105]]
map[1:[70 78 80 113 73 79] 2:[69] 3:[68 83 106] 4:[120 89] 12:[67 76] 14:[87] 18:[118 107] 20:[119] 31:[103] 36:[102 109] 39:[121] 45:[98] 53:[100] 66:[117] 69:[108] 73:[104] 81:[99] 117:[97] 142:[114] 160:[110] 177:[111] 178:[105]]
map[1:[70 78 80 113 73 79 122] 2:[69] 3:[68 83 106] 4:[120 89] 12:[67 76] 14:[87] 18:[118 107] 20:[119] 31:[103] 36:[102 109] 39:[121] 45:[98] 53:[100] 66:[117] 69:[108] 73:[104] 81:[99] 117:[97] 142:[114] 160:[110] 177:[111] 178:[105]]
map[1:[70 78 80 113 73 79 122] 2:[69] 3:[68 83 106] 4:[120 89] 12:[67 76] 14:[87] 18:[118 107] 20:[119] 31:[103] 36:[102 109] 39:[121] 45:[98] 53:[100] 66:[117] 69:[108] 73:[104] 81:[99] 111:[115] 117:[97] 142:[114] 160:[110] 177:[111] 178:[105]]
map[1:[70 78 80 113 73 79 122] 2:[69] 3:[68 83 106] 4:[120 89] 12:[67 76] 14:[87] 18:[118 107] 20:[119] 31:[103] 36:[102 109] 39:[121] 45:[98] 53:[100] 66:[117] 69:[108] 73:[104] 81:[99] 111:[115] 117:[97] 142:[114] 160:[110] 177:[111] 178:[105] 193:[101]]
map[1:[70 78 80 113 73 79 122] 2:[69] 3:[68 83 106] 4:[120 89] 12:[67 76] 14:[87] 18:[118 107] 20:[119] 31:[103] 35:[112] 36:[102 109] 39:[121] 45:[98] 53:[100] 66:[117] 69:[108] 73:[104] 81:[99] 111:[115] 117:[97] 142:[114] 160:[110] 177:[111] 178:[105] 193:[101]]
map[1:[70 78 80 113 73 79 122] 2:[69 71] 3:[68 83 106] 4:[120 89] 12:[67 76] 14:[87] 18:[118 107] 20:[119] 31:[103] 35:[112] 36:[102 109] 39:[121] 45:[98] 53:[100] 66:[117] 69:[108] 73:[104] 81:[99] 111:[115] 117:[97] 142:[114] 160:[110] 177:[111] 178:[105] 193:[101]]
map[1:[70 78 80 113 73 79 122] 2:[69 71] 3:[68 83 106] 4:[120 89] 12:[67 76] 14:[87] 18:[118 107] 20:[119] 31:[103] 35:[112] 36:[102 109] 39:[121] 45:[98] 53:[100] 66:[117] 69:[108] 73:[104] 81:[99] 111:[115] 117:[97] 142:[114] 160:[110] 177:[111] 178:[105] 193:[101] 197:[116]]

练习题5#

sort排序

比如,对下面数组进行排序

nums := []int{1,7,8,9,2}
sort.Ints(nums)

如下:

package main
import (
    "fmt"
    "sort"
)
func main(){
    nums := []int{1,7,8,9,2}
    sort.Ints(nums)
    fmt.Println(nums)
}

运行

[root@DT_Node-172_17_0_1 /opt/Golang/work2]# go run work11.go
[1 2 7 8 9] 

二分查找是在有序的数组中查找元素,仍然可以使用sort来做sort.SearchInts

nums := []int{1,7,8,9,2}

比如,查看8在nums中的索引位置

sort.SearchInts(nums,8)

代码块

package main
import (
    "fmt"
    "sort"
)
func main(){

    nums := []int{1,7,8,9,2}
    fmt.Println(sort.SearchInts(nums,8))
}

运行

[root@DT_Node-172_17_0_1 /opt/Golang/work2]# go run work12.go
2

如果查找的值不在数组中,会打印什么?

比如,查10

    nums := []int{1,7,8,9,2,20}
    fmt.Println(sort.SearchInts(nums,10))

运行

[root@DT_Node-172_17_0_1 /opt/Golang/work2]go run work12.go
5

当我们查询10的时候,10不在nums切片数组中,但是打印的是5。这个5的位置是切片插入 后的位置,尽管现在没有插入,但是返回的是插入后的位置。

可以使用此方法来判断切片是否存在

首先接收返回值

idx := sort.SearchInts(nums,num)

而后定义一个num,num是比较的值,进行判断。如果num== nums[idx]就说明存在,否则就说明不存在。

    idx := sort.SearchInts(nums,10)
    num := 10
    if nums[idx] == num {
        fmt.Println("存在")
    } else {
        fmt.Println("不存在")
    }

修改下代码块

package main
import (
    "fmt"
    "sort"
)
func main(){

    nums := []int{1,7,8,9,2,20}

    num := 10
    idx := sort.SearchInts(nums,num)
//  if nums[sort.SearchInts(nums,num)] == num { 
    if nums[idx] == num {
        fmt.Println("存在")
    } else {
        fmt.Println("不存在")
    }
}

运行

[root@DT_Node-172_17_0_1 /opt/Golang/work2]# go run work12.go
不存在