当前位置: 首页 > news >正文

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 := 6fmt.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 := 75switch { // expression is omittedcase 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)fallthroughcase num < 100:fmt.Printf("%d is lesser than 100\n", num)fallthroughcase 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整除的ifmt.Printf("Generated even number %d", i)break randloop	// 必须添加break}}///  Generated even number 86

二. Arrays数组

	var a [3]int //	int array with length 3a[0] = 11a[1] = 12a[2] = 13b := [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 ff[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 mainimport "fmt"func changeLocal(num [5]int) {  num[0] = 22fmt.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 valuefmt.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.00a := [...]float64{13.14, 14.13, 15.20, 21, 52}sum := float64(0)for i, v := range a { //range returns both the index and valuefmt.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.00a := [...]float64{13.14, 14.13, 15.20, 21, 52}sum := float64(0)for i, v := range a { //range returns both the index and valuefmt.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 100fmt.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]// 实例2numa := [3]int{78, 79, 80}nums1 := numa[:] //creates a slice which contains all elements of the arraynums2 := numa[:]fmt.Println("array before change 1", numa) // [78 79 80]nums1[0] = 100fmt.Println("array after modification to slice nums1", numa) // [100 79 80]nums2[1] = 101fmt.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 6fruitslice = 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 mainimport (  "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 3cars = append(cars, "Toyota")fmt.Println("cars:", cars, "has new length", len(cars), "and capacity", cap(cars)) //capacity of cars is doubled to 6 容量自动变大// 实例2var names []string	//zero value of a slice is nilif names == nil { // nil == Nonefmt.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 = valuesfmt.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 slicefmt.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:6neededCountries := countries[:len(countries)-2]                                     // len:4, cap:6countriesCpy := make([]string, len(neededCountries))                                // len:4, cap:4copy(countriesCpy, neededCountries)                                                 // copy the make cap , values is neededCountriesreturn countriesCpy                                                                 // return list}func main() {countriesNeeded := Countries() // 赋值fmt.Println(countriesNeeded)   // [China USA Singapore Germany]}

相关文章:

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

文章目录 一. Switch语句1. Default case2. Multiple expressions in case3. Expressionless switch4. Fallthrough5. break6. break for loop 二. Arrays数组1. when arrays are passed to functions as parameters2. Iterating arrays using range3.Multidimensional arrays …...

从URL取值传给后端

从URL传值给后端 http://127.0.0.1:8080/blog_content.html?id8点击浏览文章详情&#xff0c;跳转至详情页面 从 url 中拿出文章 id&#xff0c;传给后端 首先拿到url然后判断是否有值&#xff0c;从问号后面取值params.split(&) 以 & 作为分割然后遍历字符数组 param…...

API接口用例生成器

一、前言 随着自动化测试技术的普及&#xff0c;已经有很多公司或项目&#xff0c;多多少少都会进行自动化测试。 目前本部门的自动化测试以接口自动化为主&#xff0c;接口用例采用 Excel 进行维护&#xff0c;按照既定的接口用例编写规则&#xff0c;对于功能测试人员来说只…...

最新AI创作系统ChatGPT源码V2.5.8/支持GPT4.0+GPT联网提问/支持ai绘画Midjourney+Prompt+MJ以图生图+思维导图生成!

使用Nestjs和Vue3框架技术&#xff0c;持续集成AI能力到系统&#xff01; 最新版【V2.5.8】更新&#xff1a; 新增 MJ 官方图片重新生成指令功能同步官方 Vary 指令 单张图片对比加强 Vary(Strong) | Vary(Subtle)同步官方 Zoom 指令 单张图片无限缩放 Zoom out 2x | Zoom ou…...

【Vxworks】映射物理地址为虚拟地址,并获取此地址的存放值

最近开始接触Vxworks&#xff0c;得知Vx中不可对物理地址直接操作&#xff0c;需要先转为虚拟地址。 本文则将介绍此实现方法。 1. 物理地址映射为虚拟地址 采用pmapGlobalMap接口&#xff0c;对从0xf0000000开始&#xff0c;大小为0x1000的地址空间进行映射&#xff0c;得到…...

C/C++可变参数列表

可变参数列表 可变参数宏--__VA_ARGS__C风格不定参使用补充知识&#xff1a;函数调用时参数的压栈顺序及内存使用使用不定参模拟实现printf C风格不定参数的使用 可变参数宏–VA_ARGS #include <stdio.h>//...表示不定参&#xff0c;__VA_ARGS__使用不定参 // __FILE__ …...

MongoDB基本命令使用

成功启动MongoDB后&#xff0c;再打开一个命令行窗口输入mongo&#xff0c;就可以进行数据库的一些操作。 输入help可以看到基本操作命令&#xff1a; show dbs:显示数据库列表 show collections&#xff1a;显示当前数据库中的集合&#xff08;类似关系数据库中的表&#xf…...

uniapp 微信小程序 上下滚动的公告通知(只取前3条)

效果图&#xff1a; <template><view class"notice" click"policyInformation"><view class"notice-icon"><image mode"aspectFit" class"img" src"/static/img/megaphone.png"></i…...

OSPF在MGRE上的实验

实验题目如下&#xff1a; 实验拓扑如下&#xff1a; 实验要求如下&#xff1a; 【1】R6为ISP只能配置ip地址&#xff0c;R1-5的环回为私有网段 【2】R1/4/5为全连的MGRE结构&#xff0c;R1/2/3为星型的拓扑结构&#xff0c;R1为中心站点 【3】所有私有网段可以互相通讯&…...

什么样的跨网文件安全交换系统 可实现安全便捷的文件摆渡?

进入互联网时代&#xff0c;网络的运算和数据管理能力助力各个行业高速发展&#xff0c;但同样带来了一些网络安全隐患&#xff0c;网络攻击、数据窃取、敏感信息泄露等问题。为此&#xff0c;我国出台了系列政策来全面提升银各行业系统网络安全整体防护水平&#xff0c;其中“…...

C语言memset函数的作用

memset函数是C语言中的一个库函数&#xff0c;其作用是将一块内存区域的每个字节都设置为指定的值。 memset函数的原型如下&#xff1a; void *memset(void *ptr, int value, size_t num); 参数解释&#xff1a; ptr&#xff1a;指向要填充的内存区域的指针。value&#xff1…...

暑假刷题第23天--8/7

D-游游的k-好数组_牛客周赛 Round 6 (nowcoder.com)&#xff08;关键--a[1]a[k1]&#xff09; #include<iostream> #include<algorithm> using namespace std; const int N100005; int a[N]; typedef pair<int,int>PII; PII b[N]; void solve(){int n,k,x;…...

Double DQN缓解动作价值的高估问题

1、算法&#xff1a; Selection using DQN&#xff1a; a ⋆ argmax ⁡ a Q ( s t 1 , a ; w ) . a^{\star}\operatorname*{argmax}_{a}Q(s_{t1},a;\mathbf{w}). a⋆aargmax​Q(st1​,a;w). Evaluation using target network: y t r t γ ⋅ Q ( s t 1 , a ⋆ ; w − )…...

【C#学习笔记】内存管理

文章目录 分配内存释放内存GC标记清除算法分代算法大对象和小对象 .NET的GC机制有这样两个问题&#xff1a; 官方文档 自动内存管理 自动内存管理是CLR在托管执行过程中提供的服务之一。 公共语言运行时的垃圾回收器为应用程序管理内存的分配和释放。 对开发人员而言&#xf…...

面试之快速学习c++11- 列表初始化和 lambda匿名函数的定义

学习地址&#xff1a; http://c.biancheng.net/view/3730.html 8. C11列表初始化&#xff08;统一了初始化方式&#xff09; 我们知道&#xff0c;在 C98/03 中的对象初始化方法有很多种&#xff0c;请看下面的代码&#xff1a; //初始化列表 int i_arr[3] { 1, 2, 3 }; /…...

CI/CD—Docker初入门学习

1 docker 了解 1 Docker 简介 Docker 是基于 Go 语言的开源应用容器虚拟化技术。Docker的主要目标是build、ship and run any app&#xff0c;anywhere&#xff0c;即通过对应用组件的封装、分发、部署、运行等生命周期的管理&#xff0c;达到应用组件级别的一次封装、到处运…...

多线程的创建,复习匿名内部类,Thread的一些方法,以及lambda的变量捕捉,join用法

一、&#x1f49b; Java的Thread类表示线程 1.创建类&#xff0c;继承Thread重写run方法 2.创建类&#xff0c;实现Runnable重写run方法 3.可以继承Thread重写run基于匿名内部类 4.实现Runnable重写run基于匿名内部类 5.lamdba表达式表示run方法的内容&#xff08;推荐&#x…...

瑞吉外卖系统05

哈喽&#xff01;大家好&#xff0c;我是旷世奇才李先生 文章持续更新&#xff0c;可以微信搜索【小奇JAVA面试】第一时间阅读&#xff0c;回复【资料】更有我为大家准备的福利哟&#xff0c;回复【项目】获取我为大家准备的项目 最近打算把我手里之前做的项目分享给大家&#…...

D455+VINS-Fusion+surfelmapping 稠密建图(三)

继续&#xff0c;由surfelmapping建立的点云生成octomap八叉树栅格地图 一、安装OctomapServer 建图包 安装插件 sudo apt-get install ros-melodic-octomap-ros sudo apt-get install ros-melodic-octomap-msgs sudo apt-get install ros-melodic-octomap-server sudo apt-…...

rv1109/1126 rknn 模型部署过程

rv1109/1126是瑞芯微出的嵌入式AI芯片&#xff0c;带有npu, 可以用于嵌入式人工智能应用。算法工程师训练出的算法要部署到芯片上&#xff0c;需要经过模型转换和量化&#xff0c;下面记录一下整个过程。 量化环境 模型量化需要安装rk的工具包&#xff1a; rockchip-linux/rk…...

Chapter03-Authentication vulnerabilities

文章目录 1. 身份验证简介1.1 What is authentication1.2 difference between authentication and authorization1.3 身份验证机制失效的原因1.4 身份验证机制失效的影响 2. 基于登录功能的漏洞2.1 密码爆破2.2 用户名枚举2.3 有缺陷的暴力破解防护2.3.1 如果用户登录尝试失败次…...

利用ngx_stream_return_module构建简易 TCP/UDP 响应网关

一、模块概述 ngx_stream_return_module 提供了一个极简的指令&#xff1a; return <value>;在收到客户端连接后&#xff0c;立即将 <value> 写回并关闭连接。<value> 支持内嵌文本和内置变量&#xff08;如 $time_iso8601、$remote_addr 等&#xff09;&a…...

基于ASP.NET+ SQL Server实现(Web)医院信息管理系统

医院信息管理系统 1. 课程设计内容 在 visual studio 2017 平台上&#xff0c;开发一个“医院信息管理系统”Web 程序。 2. 课程设计目的 综合运用 c#.net 知识&#xff0c;在 vs 2017 平台上&#xff0c;进行 ASP.NET 应用程序和简易网站的开发&#xff1b;初步熟悉开发一…...

Swift 协议扩展精进之路:解决 CoreData 托管实体子类的类型不匹配问题(下)

概述 在 Swift 开发语言中&#xff0c;各位秃头小码农们可以充分利用语法本身所带来的便利去劈荆斩棘。我们还可以恣意利用泛型、协议关联类型和协议扩展来进一步简化和优化我们复杂的代码需求。 不过&#xff0c;在涉及到多个子类派生于基类进行多态模拟的场景下&#xff0c;…...

STM32标准库-DMA直接存储器存取

文章目录 一、DMA1.1简介1.2存储器映像1.3DMA框图1.4DMA基本结构1.5DMA请求1.6数据宽度与对齐1.7数据转运DMA1.8ADC扫描模式DMA 二、数据转运DMA2.1接线图2.2代码2.3相关API 一、DMA 1.1简介 DMA&#xff08;Direct Memory Access&#xff09;直接存储器存取 DMA可以提供外设…...

剑指offer20_链表中环的入口节点

链表中环的入口节点 给定一个链表&#xff0c;若其中包含环&#xff0c;则输出环的入口节点。 若其中不包含环&#xff0c;则输出null。 数据范围 节点 val 值取值范围 [ 1 , 1000 ] [1,1000] [1,1000]。 节点 val 值各不相同。 链表长度 [ 0 , 500 ] [0,500] [0,500]。 …...

Nuxt.js 中的路由配置详解

Nuxt.js 通过其内置的路由系统简化了应用的路由配置&#xff0c;使得开发者可以轻松地管理页面导航和 URL 结构。路由配置主要涉及页面组件的组织、动态路由的设置以及路由元信息的配置。 自动路由生成 Nuxt.js 会根据 pages 目录下的文件结构自动生成路由配置。每个文件都会对…...

【C语言练习】080. 使用C语言实现简单的数据库操作

080. 使用C语言实现简单的数据库操作 080. 使用C语言实现简单的数据库操作使用原生APIODBC接口第三方库ORM框架文件模拟1. 安装SQLite2. 示例代码:使用SQLite创建数据库、表和插入数据3. 编译和运行4. 示例运行输出:5. 注意事项6. 总结080. 使用C语言实现简单的数据库操作 在…...

【Linux】Linux 系统默认的目录及作用说明

博主介绍&#xff1a;✌全网粉丝23W&#xff0c;CSDN博客专家、Java领域优质创作者&#xff0c;掘金/华为云/阿里云/InfoQ等平台优质作者、专注于Java技术领域✌ 技术范围&#xff1a;SpringBoot、SpringCloud、Vue、SSM、HTML、Nodejs、Python、MySQL、PostgreSQL、大数据、物…...

MyBatis中关于缓存的理解

MyBatis缓存 MyBatis系统当中默认定义两级缓存&#xff1a;一级缓存、二级缓存 默认情况下&#xff0c;只有一级缓存开启&#xff08;sqlSession级别的缓存&#xff09;二级缓存需要手动开启配置&#xff0c;需要局域namespace级别的缓存 一级缓存&#xff08;本地缓存&#…...