当前位置: 首页 > 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…...

铭豹扩展坞 USB转网口 突然无法识别解决方法

当 USB 转网口扩展坞在一台笔记本上无法识别,但在其他电脑上正常工作时,问题通常出在笔记本自身或其与扩展坞的兼容性上。以下是系统化的定位思路和排查步骤,帮助你快速找到故障原因: 背景: 一个M-pard(铭豹)扩展坞的网卡突然无法识别了,扩展出来的三个USB接口正常。…...

挑战杯推荐项目

“人工智能”创意赛 - 智能艺术创作助手&#xff1a;借助大模型技术&#xff0c;开发能根据用户输入的主题、风格等要求&#xff0c;生成绘画、音乐、文学作品等多种形式艺术创作灵感或初稿的应用&#xff0c;帮助艺术家和创意爱好者激发创意、提高创作效率。 ​ - 个性化梦境…...

synchronized 学习

学习源&#xff1a; https://www.bilibili.com/video/BV1aJ411V763?spm_id_from333.788.videopod.episodes&vd_source32e1c41a9370911ab06d12fbc36c4ebc 1.应用场景 不超卖&#xff0c;也要考虑性能问题&#xff08;场景&#xff09; 2.常见面试问题&#xff1a; sync出…...

【JavaEE】-- HTTP

1. HTTP是什么&#xff1f; HTTP&#xff08;全称为"超文本传输协议"&#xff09;是一种应用非常广泛的应用层协议&#xff0c;HTTP是基于TCP协议的一种应用层协议。 应用层协议&#xff1a;是计算机网络协议栈中最高层的协议&#xff0c;它定义了运行在不同主机上…...

大学生职业发展与就业创业指导教学评价

这里是引用 作为软工2203/2204班的学生&#xff0c;我们非常感谢您在《大学生职业发展与就业创业指导》课程中的悉心教导。这门课程对我们即将面临实习和就业的工科学生来说至关重要&#xff0c;而您认真负责的教学态度&#xff0c;让课程的每一部分都充满了实用价值。 尤其让我…...

AGain DB和倍数增益的关系

我在设置一款索尼CMOS芯片时&#xff0c;Again增益0db变化为6DB&#xff0c;画面的变化只有2倍DN的增益&#xff0c;比如10变为20。 这与dB和线性增益的关系以及传感器处理流程有关。以下是具体原因分析&#xff1a; 1. dB与线性增益的换算关系 6dB对应的理论线性增益应为&…...

基于PHP的连锁酒店管理系统

有需要请加文章底部Q哦 可远程调试 基于PHP的连锁酒店管理系统 一 介绍 连锁酒店管理系统基于原生PHP开发&#xff0c;数据库mysql&#xff0c;前端bootstrap。系统角色分为用户和管理员。 技术栈 phpmysqlbootstrapphpstudyvscode 二 功能 用户 1 注册/登录/注销 2 个人中…...

TSN交换机正在重构工业网络,PROFINET和EtherCAT会被取代吗?

在工业自动化持续演进的今天&#xff0c;通信网络的角色正变得愈发关键。 2025年6月6日&#xff0c;为期三天的华南国际工业博览会在深圳国际会展中心&#xff08;宝安&#xff09;圆满落幕。作为国内工业通信领域的技术型企业&#xff0c;光路科技&#xff08;Fiberroad&…...

windows系统MySQL安装文档

概览&#xff1a;本文讨论了MySQL的安装、使用过程中涉及的解压、配置、初始化、注册服务、启动、修改密码、登录、退出以及卸载等相关内容&#xff0c;为学习者提供全面的操作指导。关键要点包括&#xff1a; 解压 &#xff1a;下载完成后解压压缩包&#xff0c;得到MySQL 8.…...

区块链技术概述

区块链技术是一种去中心化、分布式账本技术&#xff0c;通过密码学、共识机制和智能合约等核心组件&#xff0c;实现数据不可篡改、透明可追溯的系统。 一、核心技术 1. 去中心化 特点&#xff1a;数据存储在网络中的多个节点&#xff08;计算机&#xff09;&#xff0c;而非…...