Go语言基础: Switch语句、Arrays数组、Slices切片 详细教程案例

文章目录

  • [一. Switch语句](#一. Switch语句)
    • [1. Default case](#1. Default case)
    • [2. Multiple expressions in case](#2. Multiple expressions in case)
    • [3. Expressionless switch](#3. Expressionless switch)
    • [4. Fallthrough](#4. Fallthrough)
    • [5. break](#5. break)
    • [6. break for loop](#6. break for loop)
  • [二. Arrays数组](#二. Arrays数组)
    • [1. when arrays are passed to functions as parameters](#1. when arrays are passed to functions as parameters)
    • [2. Iterating arrays using range](#2. Iterating arrays using range)
    • [3.Multidimensional arrays 多维数组](#3.Multidimensional arrays 多维数组)
  • [三. Slices切片](#三. Slices切片)
    • [1. Creating a slice](#1. Creating a slice)
    • [2. Modifying a slice](#2. Modifying a slice)
    • [3. Length and capacity of a slice](#3. Length and capacity of a slice)
    • [4. Creating a slice using make](#4. Creating a slice using make)
    • [5. Appending to a slice](#5. Appending to a slice)
    • [6. Passing a slice to a function](#6. Passing a slice to a function)
    • [7. Multidimensional slices](#7. Multidimensional slices)
    • [7. Memory Optimisation](#7. Memory Optimisation)

一. Switch语句

1. Default case

go 复制代码
	finger := 6
	fmt.Printf("Finger %d is ", finger)
	switch finger {
	case 1:
	    fmt.Println("Thumb")
	case 2:
	    fmt.Println("Index")
	case 3:
	    fmt.Println("Middle")
	case 4: // 不能出现相同的数字
	    fmt.Println("Ring")
	case 5:
	    fmt.Println("Pinky")
	default: //default case	如果没有则执行默认
	    fmt.Println("incorrect finger number")
	}
	
	/// 输出: Finger 6 is incorrect finger number

2. Multiple expressions in case

go 复制代码
	letter := "a"
	fmt.Printf("Letter %s is a ", letter)
	switch letter {
	case "a", "b", "c", "d":
	    fmt.Println("Vowel")
	default:
	    fmt.Println("No Vowel")
	}
	
	/// 输出 Letter a is a Vowel

3. Expressionless switch

go 复制代码
	num := 75
	switch { // expression is omitted
	case num >= 0 && num <= 50:
	    fmt.Printf("%d is greater than 0 and less than 50", num)
	case num >= 51 && num <= 100:
	    fmt.Printf("%d is greater than 51 and less than 100", num)
	case num >= 101:
	    fmt.Printf("%d is greater than 100", num)
	}
	/// 75 is greater than 51 and less than 100

4. Fallthrough

go 复制代码
	switch num := 25; {
	case num < 50:
	    fmt.Printf("%d is lesser than 50\n", num)
	    fallthrough		// 关键字
	case num > 100: // 当这句是错误的 也会继续运行下一句
	    fmt.Printf("%d is greater than 100\n", num)
	}
	
	///	25 is lesser than 50
	///	25 is greater than 100

5. break

go 复制代码
	switch num := -7; {
	case num < 50:
	    if num < 0 {
	        break		// 小于0就被break了
	    }
	    fmt.Printf("%d is lesser than 50\n", num)
	    fallthrough
	case num < 100:
	    fmt.Printf("%d is lesser than 100\n", num)
	    fallthrough
	case num < 200:
	    fmt.Printf("%d is lesser than 200", num)
}

6. break for loop

go 复制代码
	randloop:
		for {
			switch i := rand.Intn(100); {	// 100以内随机数
			case i%2 == 0:	// 能被2整除的i
				fmt.Printf("Generated even number %d", i)
				break randloop	// 必须添加break
			}
		}
	///  Generated even number 86

二. Arrays数组

go 复制代码
	var a [3]int //	int array with length 3
	a[0] = 11
	a[1] = 12
	a[2] = 13
	
	b := [3]int{15, 16, 17} // 注意声明了int类型就不能是别的类型
	
	c := [3]int{18}
	
	d := [...]int{19, 20, 21}
	
	e := [...]string{"USA", "China", "India", "Germany", "France"}
	f := e // a copy of e is assigned to f
	f[0] = "Singapore"
	fmt.Println("a is ", a)
	fmt.Println("b is ", b)
	
	fmt.Println(b) // [15 16 17]
	fmt.Println(a) // [11 12 13]
	fmt.Println(c) // [18 0 0]
	fmt.Println(d) // [19 20 21]
	fmt.Println(e) // [USA China India Germany France]
	fmt.Println(f) // [Singapore China India Germany France]
	fmt.Println(len(f))	// 5	Length of an array

1. when arrays are passed to functions as parameters

go 复制代码
    package main

    import "fmt"

    func changeLocal(num [5]int) {  
        num[0] = 22
        fmt.Println("inside function ", num)

    }
    func main() {  
        num := [...]int{33, 44, 55, 66, 77}
        fmt.Println("bebore passing to function", num)
        changeLocal(num) // num is passing by value
        fmt.Println("after passing to function", num)
    }

    // bebore passing to function [33 44 55 66 77]
    // inside function [22 44 55 66 77]
    // after passing to function [33 44 55 66 77]

2. Iterating arrays using range

go 复制代码
    a := [...]float64{13.14, 14.13, 15.20, 21, 52}
    for i := 0; i < len(a); i++ {
        fmt.Printf("%d th element of a is %.2f\n", i, a[i])
    }

	// 0 th element of a is 13.14
    // 1 th element of a is 14.13
    // 2 th element of a is 15.20
    // 3 th element of a is 21.00
    // 4 th element of a is 52.00


	a := [...]float64{13.14, 14.13, 15.20, 21, 52}
	sum := float64(0)
	for i, v := range a { //range returns both the index and value
		fmt.Printf("%d the element of a is %.2f\n", i, v)
		sum += v
	}
	fmt.Println("\nsum of all elements of a", sum)

	// 0 the element of a is 13.14
    // 1 the element of a is 14.13
    // 2 the element of a is 15.20
    // 3 the element of a is 21.00
    // 4 the element of a is 52.00

    // sum of all elements of a 115.47

3.Multidimensional arrays 多维数组

go 复制代码
    a := [...]float64{13.14, 14.13, 15.20, 21, 52}
    for i := 0; i < len(a); i++ {
        fmt.Printf("%d th element of a is %.2f\n", i, a[i])
    }

	// 0 th element of a is 13.14
    // 1 th element of a is 14.13
    // 2 th element of a is 15.20
    // 3 th element of a is 21.00
    // 4 th element of a is 52.00


	a := [...]float64{13.14, 14.13, 15.20, 21, 52}
	sum := float64(0)
	for i, v := range a { //range returns both the index and value
		fmt.Printf("%d the element of a is %.2f\n", i, v)
		sum += v
	}
	fmt.Println("\nsum of all elements of a", sum)

	// 0 the element of a is 13.14
    // 1 the element of a is 14.13
    // 2 the element of a is 15.20
    // 3 the element of a is 21.00
    // 4 the element of a is 52.00

    // sum of all elements of a 115.47

三. Slices切片

1. Creating a slice

go 复制代码
	c := []int{555, 666, 777}
	fmt.Println(c)		// [555 666 777]


	a := [5]int{76, 77, 78, 79, 80}
	var b []int = a[1:4] // creates a slice from a[1] to a[3]
	fmt.Println(b)		// [77 78 79]

2. Modifying a slice

go 复制代码
	darr := [...]int{57, 89, 90, 82, 100, 78, 67, 69, 59}
	dslice := darr[2:5]               // 90 82 100
	fmt.Println("array before", darr) // array before [57 89 90 82 100 78 67 69 59]
	for i := range dslice {
		dslice[i]++ // 每一位数字+1
	}
	fmt.Println("array after", darr) // array after [57 89 91 83 101 78 67 69 59]

		
	// 实例2
	numa := [3]int{78, 79, 80}
	nums1 := numa[:] //creates a slice which contains all elements of the array
	nums2 := numa[:]
	fmt.Println("array before change 1", numa) // [78 79 80]
	nums1[0] = 100
	fmt.Println("array after modification to slice nums1", numa) // [100 79 80]
	nums2[1] = 101
	fmt.Println("array after modification to slice nums2", numa) //  [100 101 80]

3. Length and capacity of a slice

go 复制代码
	fruitarray := [...]string{"apple", "orange", "grape", "mango", "water melon", "pine apple", "chikoo"}
	fruitslice := fruitarray[1:3]
	fmt.Printf("length of slice %d capacity %d", len(fruitslice), cap(fruitslice)) //length of fruitslice is 2 and capacity is 6
	fruitslice = fruitslice[:cap(fruitslice)]
	fmt.Println(fruitslice)     // [orange grape mango water melon pine apple chikoo]
	fmt.Println("After re-slicing length is", len(fruitslice), "and capacity is ", cap(fruitslice)) // After re-slicing length is 6 and capacity is  6

4. Creating a slice using make

go 复制代码
	package main
	
	import (  
	    "fmt"
	)
	
	func main() {  
	    i := make([]int, 5, 5)
	    fmt.Println(i)
	}

5. Appending to a slice

go 复制代码
	cars := []string{"Ferrari", "Honda", "Ford"}
	fmt.Println("cars:", cars, "has old length", len(cars), "and capacity", cap(cars)) //capacity of cars is 3
	cars = append(cars, "Toyota")
	fmt.Println("cars:", cars, "has new length", len(cars), "and capacity", cap(cars)) //capacity of cars is doubled to 6 容量自动变大

	// 实例2
	var names []string	//zero value of a slice is nil
	if names == nil { // nil == None
		fmt.Println("Slice is nil going to append")
		names = append(names, "John", "Like", "Lisa")
		fmt.Println("names contents:", names)		// names contents: [John Like Lisa]
	}

6. Passing a slice to a function

go 复制代码
	func SubtactOne(numbers []int) {
	for i := range numbers { // i = index numbers = values
		fmt.Println(i, numbers)
		numbers[i] -= 2 // 每次循环-2
		}
	}

	func main() {
	nos := []int{4, 5, 6}
	fmt.Println("slice before function call", nos) // [4 5 6]
	SubtactOne(nos)                                //function modifies the slice
	fmt.Println("slice after function call", nos)  //  [2 3 4]
    }

7. Multidimensional slices

go 复制代码
	pls := [][]string{
		{"C", "C--"},
		{"Python"},
		{"JavaScript"},
		{"Go", "Rust"},
	}
	for _, v1 := range pls {
		for _, v2 := range v1 {
			fmt.Printf("%s", v2)
		}
		fmt.Printf("\n")
	}

7. Memory Optimisation

go 复制代码
	func Countries() []string {
	countries := []string{"China", "USA", "Singapore", "Germany", "India", "Australia"} // len:6, cap:6
	neededCountries := countries[:len(countries)-2]                                     // len:4, cap:6
	countriesCpy := make([]string, len(neededCountries))                                // len:4, cap:4
	copy(countriesCpy, neededCountries)                                                 // copy the make cap , values is neededCountries
	return countriesCpy                                                                 // return list
	}
    func main() {
        countriesNeeded := Countries() // 赋值
        fmt.Println(countriesNeeded)   // [China USA Singapore Germany]
    }
相关推荐
ruleslol几秒前
java基础概念37:正则表达式2-爬虫
java
懒是一种态度1 分钟前
Golang 调用 mongodb 的函数
数据库·mongodb·golang
I_Am_Me_6 分钟前
【JavaEE进阶】 JavaScript
开发语言·javascript·ecmascript
yyt_cdeyyds7 分钟前
FIFO和LRU算法实现操作系统中主存管理
算法
重生之我是数学王子16 分钟前
QT基础 编码问题 定时器 事件 绘图事件 keyPressEvent QT5.12.3环境 C++实现
开发语言·c++·qt
xmh-sxh-131417 分钟前
jdk各个版本介绍
java
Ai 编码助手18 分钟前
使用php和Xunsearch提升音乐网站的歌曲搜索效果
开发语言·php
学习前端的小z22 分钟前
【前端】深入理解 JavaScript 逻辑运算符的优先级与短路求值机制
开发语言·前端·javascript
神仙别闹30 分钟前
基于C#和Sql Server 2008实现的(WinForm)订单生成系统
开发语言·c#
XINGTECODE31 分钟前
海盗王集成网关和商城服务端功能golang版
开发语言·后端·golang