GO基础语法 3| 青训营笔记

24 阅读2分钟

这是我参与「第五届青训营 」伴学笔记创作活动的第 10 天

Go 语言切片(Slice)

Go 语言切片是对数组的抽象。

Go 数组的长度不可改变,在特定场景中这样的集合就不太适用,Go 中提供了一种灵活,功能强悍的内置类型切片("动态数组"),与数组相比切片的长度是不固定的,可以追加元素,在追加时可能使切片的容量增大。

定义切片

var identifier []type
slice1 := make([]type, len)

切片初始化

s :=[] int {1,2,3 } 

直接初始化切片,[] 表示是切片类型, {1,2,3}  初始化值依次是 1,2,3,其 cap=len=3

s := arr[:] 

初始化切片 s,是数组 arr 的引用。

s := arr[startIndex:endIndex] 

将 arr 中从下标 startIndex 到 endIndex-1 下的元素创建为一个新的切片。

s := arr[startIndex:] 

默认 endIndex 时将表示一直到arr的最后一个元素。

s := arr[:endIndex] 

默认 startIndex 时将表示从 arr 的第一个元素开始。

s1 := s[startIndex:endIndex] 

通过切片 s 初始化切片 s1。

s :=make([]int,len,cap) 

通过内置函数 make()  初始化切片s[]int 标识为其元素类型为 int 的切片。

Go 语言范围(Range)

Go 语言中 range 关键字用于 for 循环中迭代数组(array)、切片(slice)、通道(channel)或集合(map)的元素。在数组和切片中它返回元素的索引和索引对应的值,在集合中返回 key-value 对。

for 循环的 range 格式可以对 slice、map、数组、字符串等进行迭代循环。格式如下:

for key, value := range oldMap {
    newMap[key] = value
}

以上代码中的 key 和 value 是可以省略。

如果只想读取 key,格式如下:

for key := range oldMap

或者这样:

for key, _ := range oldMap

如果只想读取 value,格式如下:

for _, value := range oldMap
package main  
import "fmt"  
  
func main() {  
    map1 := make(map[int]float32)  
    map1[1] = 1.0  
    map1[2] = 2.0  
    map1[3] = 3.0  
    map1[4] = 4.0  
     
    // 读取 key 和 value  
    for key, value := range map1 {  
      fmt.Printf("key is: %d - value is: %f\n", key, value)  
    }  
  
    // 读取 key  
    for key := range map1 {  
      fmt.Printf("key is: %d\n", key)  
    }  
  
    // 读取 value  
    for _, value := range map1 {  
      fmt.Printf("value is: %f\n", value)  
    }  
}
package main  
  
import (  
        "fmt"  
        "time"  
)  
  
func say(s string) {  
        for i := 0; i < 5; i++ {  
                time.Sleep(100 * time.Millisecond)  
                fmt.Println(s)  
        }  
}  
  
func main() {  
        go say("world")  
        say("hello")  
}

map使用

package main  
  
import "fmt"  
  
func main() {  
    var countryCapitalMap map[string]string /*创建集合 */  
    countryCapitalMap = make(map[string]string)  
  
    /* map插入key - value对,各个国家对应的首都 */  
    countryCapitalMap [ "France" ] = "巴黎"  
    countryCapitalMap [ "Italy" ] = "罗马"  
    countryCapitalMap [ "Japan" ] = "东京"  
    countryCapitalMap [ "India" ] = "新德里"  
  
    /*使用键输出地图值 */  
    for country := range countryCapitalMap {  
        fmt.Println(country, "首都是", countryCapitalMap [country])  
    }  
  
    /*查看元素在集合中是否存在 */  
    capital, ok := countryCapitalMap [ "American" ] /*如果确定是真实的,则存在,否则不存在 */  
    /*fmt.Println(capital) */  
    /*fmt.Println(ok) */  
    if (ok) {  
        fmt.Println("American 的首都是", capital)  
    } else {  
        fmt.Println("American 的首都不存在")  
    }  
}

参考连接

www.runoob.com/go/go-range…