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

这篇具有很好参考价值的文章主要介绍了Go语言基础: Switch语句、Arrays数组、Slices切片 详细教程案例。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

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

文章来源地址https://www.toymoban.com/news/detail-626781.html

到了这里,关于Go语言基础: Switch语句、Arrays数组、Slices切片 详细教程案例的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • VHDL语言基础-基本语句

    目录 VHDL基本语句: 并行语句: 并行语句常包括以下七种: 赋值语句: 使用格式: 条件赋值语句: 使用格式: 选择信号赋值语句: 使用格式: 进程语句: 使用格式: Example:D触发器: 进程语句的特点: 元件例化语句: 元件例化语句——Example:4输入与门 生成语句:

    2023年04月25日
    浏览(30)
  • 【C语言基础考研向】08判断语句与循环语句

    算术运算符的优先级高于关系运算符、关系运算符的优先级高于逻辑与和逻辑或运算符、相同优先级的运算符从左至右进行结合等,那么表达式5384-!0的最终值是多少?其计算过程如下图所示。 引入:在你打开衣柜拿出最上面的一件衣服时,你会判断这件衣服是不是你想穿的.如

    2024年01月22日
    浏览(38)
  • 【go语言基础】go中的方法

    先思考一个问题,什么是方法,什么是函数? 方法是从属于某个结构体或者非结构体的。在func这个和方法名中间加了一个特殊的接收器类型,这个接收器可以是结构体类型的或者是非结构体类型的。从属的结构体获取该方法。 函数则没有这种从属关系。 小结: 大多

    2024年02月13日
    浏览(24)
  • Go语言基础

    参考书籍《Go程序设计语言》 学习Go语言基础,并记录相关知识和代码。 创建helloworld.go 输出命令行参数 使用range简化 使用Join简化 版本二,文件与命令行 go 可以方便的创建服务器,并且有并发性。 Go并发获取多个URL 简单服务器 带有并发锁的计数服务器 显示相关协议与表单

    2024年02月11日
    浏览(37)
  • Go语言基础(一)

    本文档参考golang官方文档以及一些教程书籍,若文档有错误,欢迎issue 🤗 https://go.dev/doc/tutorial/ 参考书籍《Go语言开发实战》 Go语言是Google公司发布的一种静态型、编译型的开源编程语言,是新时代的 C语言 。Go语言已经成为 云计算时代 的重要基础编程语言。 2012年3月28日,

    2024年02月06日
    浏览(28)
  • go语言基础---8

    go语言标准库内建提供了net/http包,涵盖了HTTP客户端和服务端的具体实现。使用net/http包,我们可以很方便地编写HTTP客户端或服务端的程序。 ListenAndServe监听TCP地址addr,并且会使用handler参数调用Serve函数处理接收到的连接。handler参数一般会设为nil,此时会使用DefaultServeMux。

    2024年02月09日
    浏览(27)
  • Go语言基础知识(一):基础介绍

    Go 语言又称 Golang,由 Google 公司于 2009 年发布,近几年伴随着云计算、微服务、分布式的发展而迅速崛起,跻身主流编程语言之列,和 Java 类似,它是一门静态的、强类型的、编译型编程语言,为并发而生,所以天生适用于并发编程(网络编程)。 目前 Go 语言支持 Windows、

    2024年02月13日
    浏览(33)
  • Go语言基础之函数

    Go语言中支持函数、匿名函数和闭包,并且函数在Go语言中属于“一等公民”。 函数定义 Go语言中定义函数使用func,具体格式如下: 其中: 函数名:由字母、数字、下划线组成。但函数名的第一个字母不能是数字。在同一个包内,函数名也称不能重名(包的概念详见

    2024年02月11日
    浏览(25)
  • go语言基础操作---七

    什么是Socket Socket,英文含义是【插座、插孔】,一般称之为套接字,用于描述IP地址和端口。可以实现不同程序间的数据通信。 Socket起源于Unix,而Unix基本哲学之一就是“一切皆文件”,都可以用“打开open – 读写write/read – 关闭close”模式来操作。Socket就是该模式的一个实

    2024年02月09日
    浏览(25)
  • Go语言基础之切片

    切片(Slice)是一个拥有相同类型元素的可变长度的序列。它是基于数组类型做的一层封装。它非常灵活,支持自动扩容。 切片是一个引用类型,它的内部结构包含地址、长度和容量。切片一般用于快速地操作一块数据集合 声明切片类型的基本语法如下: 其中, name:表示变

    2024年02月11日
    浏览(39)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包