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点击浏览文章详情,跳转至详情页面 从 url 中拿出文章 id,传给后端 首先拿到url然后判断是否有值,从问号后面取值params.split(&) 以 & 作为分割然后遍历字符数组 param…...
API接口用例生成器
一、前言 随着自动化测试技术的普及,已经有很多公司或项目,多多少少都会进行自动化测试。 目前本部门的自动化测试以接口自动化为主,接口用例采用 Excel 进行维护,按照既定的接口用例编写规则,对于功能测试人员来说只…...
最新AI创作系统ChatGPT源码V2.5.8/支持GPT4.0+GPT联网提问/支持ai绘画Midjourney+Prompt+MJ以图生图+思维导图生成!
使用Nestjs和Vue3框架技术,持续集成AI能力到系统! 最新版【V2.5.8】更新: 新增 MJ 官方图片重新生成指令功能同步官方 Vary 指令 单张图片对比加强 Vary(Strong) | Vary(Subtle)同步官方 Zoom 指令 单张图片无限缩放 Zoom out 2x | Zoom ou…...
【Vxworks】映射物理地址为虚拟地址,并获取此地址的存放值
最近开始接触Vxworks,得知Vx中不可对物理地址直接操作,需要先转为虚拟地址。 本文则将介绍此实现方法。 1. 物理地址映射为虚拟地址 采用pmapGlobalMap接口,对从0xf0000000开始,大小为0x1000的地址空间进行映射,得到…...
C/C++可变参数列表
可变参数列表 可变参数宏--__VA_ARGS__C风格不定参使用补充知识:函数调用时参数的压栈顺序及内存使用使用不定参模拟实现printf C风格不定参数的使用 可变参数宏–VA_ARGS #include <stdio.h>//...表示不定参,__VA_ARGS__使用不定参 // __FILE__ …...
MongoDB基本命令使用
成功启动MongoDB后,再打开一个命令行窗口输入mongo,就可以进行数据库的一些操作。 输入help可以看到基本操作命令: show dbs:显示数据库列表 show collections:显示当前数据库中的集合(类似关系数据库中的表…...
uniapp 微信小程序 上下滚动的公告通知(只取前3条)
效果图: <template><view class"notice" click"policyInformation"><view class"notice-icon"><image mode"aspectFit" class"img" src"/static/img/megaphone.png"></i…...
OSPF在MGRE上的实验
实验题目如下: 实验拓扑如下: 实验要求如下: 【1】R6为ISP只能配置ip地址,R1-5的环回为私有网段 【2】R1/4/5为全连的MGRE结构,R1/2/3为星型的拓扑结构,R1为中心站点 【3】所有私有网段可以互相通讯&…...
什么样的跨网文件安全交换系统 可实现安全便捷的文件摆渡?
进入互联网时代,网络的运算和数据管理能力助力各个行业高速发展,但同样带来了一些网络安全隐患,网络攻击、数据窃取、敏感信息泄露等问题。为此,我国出台了系列政策来全面提升银各行业系统网络安全整体防护水平,其中“…...
C语言memset函数的作用
memset函数是C语言中的一个库函数,其作用是将一块内存区域的每个字节都设置为指定的值。 memset函数的原型如下: void *memset(void *ptr, int value, size_t num); 参数解释: ptr:指向要填充的内存区域的指针。value࿱…...
暑假刷题第23天--8/7
D-游游的k-好数组_牛客周赛 Round 6 (nowcoder.com)(关键--a[1]a[k1]) #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、算法: Selection using DQN: a ⋆ argmax a Q ( s t 1 , a ; w ) . a^{\star}\operatorname*{argmax}_{a}Q(s_{t1},a;\mathbf{w}). a⋆aargmaxQ(st1,a;w). Evaluation using target network: y t r t γ ⋅ Q ( s t 1 , a ⋆ ; w − )…...
【C#学习笔记】内存管理
文章目录 分配内存释放内存GC标记清除算法分代算法大对象和小对象 .NET的GC机制有这样两个问题: 官方文档 自动内存管理 自动内存管理是CLR在托管执行过程中提供的服务之一。 公共语言运行时的垃圾回收器为应用程序管理内存的分配和释放。 对开发人员而言…...
面试之快速学习c++11- 列表初始化和 lambda匿名函数的定义
学习地址: http://c.biancheng.net/view/3730.html 8. C11列表初始化(统一了初始化方式) 我们知道,在 C98/03 中的对象初始化方法有很多种,请看下面的代码: //初始化列表 int i_arr[3] { 1, 2, 3 }; /…...
CI/CD—Docker初入门学习
1 docker 了解 1 Docker 简介 Docker 是基于 Go 语言的开源应用容器虚拟化技术。Docker的主要目标是build、ship and run any app,anywhere,即通过对应用组件的封装、分发、部署、运行等生命周期的管理,达到应用组件级别的一次封装、到处运…...
多线程的创建,复习匿名内部类,Thread的一些方法,以及lambda的变量捕捉,join用法
一、💛 Java的Thread类表示线程 1.创建类,继承Thread重写run方法 2.创建类,实现Runnable重写run方法 3.可以继承Thread重写run基于匿名内部类 4.实现Runnable重写run基于匿名内部类 5.lamdba表达式表示run方法的内容(推荐&#x…...
瑞吉外卖系统05
哈喽!大家好,我是旷世奇才李先生 文章持续更新,可以微信搜索【小奇JAVA面试】第一时间阅读,回复【资料】更有我为大家准备的福利哟,回复【项目】获取我为大家准备的项目 最近打算把我手里之前做的项目分享给大家&#…...
D455+VINS-Fusion+surfelmapping 稠密建图(三)
继续,由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芯片,带有npu, 可以用于嵌入式人工智能应用。算法工程师训练出的算法要部署到芯片上,需要经过模型转换和量化,下面记录一下整个过程。 量化环境 模型量化需要安装rk的工具包: rockchip-linux/rk…...
React hook之useRef
React useRef 详解 useRef 是 React 提供的一个 Hook,用于在函数组件中创建可变的引用对象。它在 React 开发中有多种重要用途,下面我将全面详细地介绍它的特性和用法。 基本概念 1. 创建 ref const refContainer useRef(initialValue);initialValu…...
VB.net复制Ntag213卡写入UID
本示例使用的发卡器:https://item.taobao.com/item.htm?ftt&id615391857885 一、读取旧Ntag卡的UID和数据 Private Sub Button15_Click(sender As Object, e As EventArgs) Handles Button15.Click轻松读卡技术支持:网站:Dim i, j As IntegerDim cardidhex, …...
前端倒计时误差!
提示:记录工作中遇到的需求及解决办法 文章目录 前言一、误差从何而来?二、五大解决方案1. 动态校准法(基础版)2. Web Worker 计时3. 服务器时间同步4. Performance API 高精度计时5. 页面可见性API优化三、生产环境最佳实践四、终极解决方案架构前言 前几天听说公司某个项…...
使用分级同态加密防御梯度泄漏
抽象 联邦学习 (FL) 支持跨分布式客户端进行协作模型训练,而无需共享原始数据,这使其成为在互联和自动驾驶汽车 (CAV) 等领域保护隐私的机器学习的一种很有前途的方法。然而,最近的研究表明&…...
汇编常见指令
汇编常见指令 一、数据传送指令 指令功能示例说明MOV数据传送MOV EAX, 10将立即数 10 送入 EAXMOV [EBX], EAX将 EAX 值存入 EBX 指向的内存LEA加载有效地址LEA EAX, [EBX4]将 EBX4 的地址存入 EAX(不访问内存)XCHG交换数据XCHG EAX, EBX交换 EAX 和 EB…...
有限自动机到正规文法转换器v1.0
1 项目简介 这是一个功能强大的有限自动机(Finite Automaton, FA)到正规文法(Regular Grammar)转换器,它配备了一个直观且完整的图形用户界面,使用户能够轻松地进行操作和观察。该程序基于编译原理中的经典…...
MFC 抛体运动模拟:常见问题解决与界面美化
在 MFC 中开发抛体运动模拟程序时,我们常遇到 轨迹残留、无效刷新、视觉单调、物理逻辑瑕疵 等问题。本文将针对这些痛点,详细解析原因并提供解决方案,同时兼顾界面美化,让模拟效果更专业、更高效。 问题一:历史轨迹与小球残影残留 现象 小球运动后,历史位置的 “残影”…...
C#学习第29天:表达式树(Expression Trees)
目录 什么是表达式树? 核心概念 1.表达式树的构建 2. 表达式树与Lambda表达式 3.解析和访问表达式树 4.动态条件查询 表达式树的优势 1.动态构建查询 2.LINQ 提供程序支持: 3.性能优化 4.元数据处理 5.代码转换和重写 适用场景 代码复杂性…...
Git常用命令完全指南:从入门到精通
Git常用命令完全指南:从入门到精通 一、基础配置命令 1. 用户信息配置 # 设置全局用户名 git config --global user.name "你的名字"# 设置全局邮箱 git config --global user.email "你的邮箱example.com"# 查看所有配置 git config --list…...
ubuntu22.04 安装docker 和docker-compose
首先你要确保没有docker环境或者使用命令删掉docker sudo apt-get remove docker docker-engine docker.io containerd runc安装docker 更新软件环境 sudo apt update sudo apt upgrade下载docker依赖和GPG 密钥 # 依赖 apt-get install ca-certificates curl gnupg lsb-rel…...
