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

文章目录

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

一. Switch语句

1. Default case

	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

	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

	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

	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

	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

	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数组

	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

    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

    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 多维数组

    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

	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

	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

	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

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

5. Appending to a slice

	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

	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

	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

	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]
    }

你可能感兴趣的:(Go,golang,java,算法,开发语言,go)