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

SpringBoot-17-MyBatis动态SQL标签之常用标签

文章目录 1 代码1.1 实体User.java1.2 接口UserMapper.java1.3 映射UserMapper.xml1.3.1 标签if1.3.2 标签if和where1.3.3 标签choose和when和otherwise1.4 UserController.java2 常用动态SQL标签2.1 标签set2.1.1 UserMapper.java2.1.2 UserMapper.xml2.1.3 UserController.ja…...

华为OD机试-食堂供餐-二分法

import java.util.Arrays; import java.util.Scanner;public class DemoTest3 {public static void main(String[] args) {Scanner in new Scanner(System.in);// 注意 hasNext 和 hasNextLine 的区别while (in.hasNextLine()) { // 注意 while 处理多个 caseint a in.nextIn…...

(转)什么是DockerCompose?它有什么作用?

一、什么是DockerCompose? DockerCompose可以基于Compose文件帮我们快速的部署分布式应用&#xff0c;而无需手动一个个创建和运行容器。 Compose文件是一个文本文件&#xff0c;通过指令定义集群中的每个容器如何运行。 DockerCompose就是把DockerFile转换成指令去运行。 …...

MFC 抛体运动模拟:常见问题解决与界面美化

在 MFC 中开发抛体运动模拟程序时,我们常遇到 轨迹残留、无效刷新、视觉单调、物理逻辑瑕疵 等问题。本文将针对这些痛点,详细解析原因并提供解决方案,同时兼顾界面美化,让模拟效果更专业、更高效。 问题一:历史轨迹与小球残影残留 现象 小球运动后,历史位置的 “残影”…...

Elastic 获得 AWS 教育 ISV 合作伙伴资质,进一步增强教育解决方案产品组合

作者&#xff1a;来自 Elastic Udayasimha Theepireddy (Uday), Brian Bergholm, Marianna Jonsdottir 通过搜索 AI 和云创新推动教育领域的数字化转型。 我们非常高兴地宣布&#xff0c;Elastic 已获得 AWS 教育 ISV 合作伙伴资质。这一重要认证表明&#xff0c;Elastic 作为 …...

Kubernetes 节点自动伸缩(Cluster Autoscaler)原理与实践

在 Kubernetes 集群中&#xff0c;如何在保障应用高可用的同时有效地管理资源&#xff0c;一直是运维人员和开发者关注的重点。随着微服务架构的普及&#xff0c;集群内各个服务的负载波动日趋明显&#xff0c;传统的手动扩缩容方式已无法满足实时性和弹性需求。 Cluster Auto…...

算术操作符与类型转换:从基础到精通

目录 前言&#xff1a;从基础到实践——探索运算符与类型转换的奥秘 算术操作符超级详解 算术操作符&#xff1a;、-、*、/、% 赋值操作符&#xff1a;和复合赋值 单⽬操作符&#xff1a;、--、、- 前言&#xff1a;从基础到实践——探索运算符与类型转换的奥秘 在先前的文…...

SQL进阶之旅 Day 22:批处理与游标优化

【SQL进阶之旅 Day 22】批处理与游标优化 文章简述&#xff08;300字左右&#xff09; 在数据库开发中&#xff0c;面对大量数据的处理任务时&#xff0c;单条SQL语句往往无法满足性能需求。本篇文章聚焦“批处理与游标优化”&#xff0c;深入探讨如何通过批量操作和游标技术提…...

Linux【5】-----编译和烧写Linux系统镜像(RK3568)

参考&#xff1a;讯为 1、文件系统 不同的文件系统组成了&#xff1a;debian、ubuntu、buildroot、qt等系统 每个文件系统的uboot和kernel是一样的 2、源码目录介绍 目录 3、正式编译 编译脚本build.sh 帮助内容如下&#xff1a; Available options: uboot …...

【前端实战】如何让用户回到上次阅读的位置?

目录 【前端实战】如何让用户回到上次阅读的位置&#xff1f; 一、总体思路 1、核心目标 2、涉及到的技术 二、实现方案详解 1、基础方法&#xff1a;监听滚动&#xff0c;记录 scrollTop&#xff08;不推荐&#xff09; 2、Intersection Observer 插入探针元素 3、基…...