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

终极指南:3个阶段让旧款Mac免费升级到最新macOS系统

终极指南&#xff1a;3个阶段让旧款Mac免费升级到最新macOS系统 【免费下载链接】OpenCore-Legacy-Patcher Experience macOS just like before 项目地址: https://gitcode.com/GitHub_Trending/op/OpenCore-Legacy-Patcher 你是否拥有一台2012-2017年的旧款Mac&#xf…...

dify可以干什么

Dify 是一个开源的大模型&#xff08;LLM&#xff09;应用开发平台&#xff0c;旨在帮助你快速构建、管理和部署生成式 AI 应用&#xff0c;而无需从零开始写代码。简单来说&#xff0c;你可以把它理解为一个可视化的 AI 应用“工作台”&#xff0c;通过拖拉拽的方式&#xff0…...

【GUI-Agent】阶跃星辰 GUI-MCP 解读---()---执行层

基础示例&#xff1a;单工作表 Excel 转 TXT 以下是将一个 Excel 文件中的第一个工作表转换为 TXT 的完整步骤&#xff1a; 1. 加载并读取Excel文件 from spire.xls import * from spire.xls.common import * workbook Workbook() workbook.LoadFromFile("示例.xlsx"…...

LongCat-Image-Editn V2效果展示:看AI如何精准将图中的猫变成狗

LongCat-Image-Editn V2效果展示&#xff1a;看AI如何精准将图中的猫变成狗 1. 效果惊艳开场&#xff1a;当AI成为你的修图助手 想象一下这样的场景&#xff1a;你拍了一张完美的照片&#xff0c;构图、光线、背景都无可挑剔&#xff0c;唯一的遗憾是照片里的主角——你的猫咪…...

突破描边技术瓶颈:从卡顿到丝滑的URP实现方案

突破描边技术瓶颈&#xff1a;从卡顿到丝滑的URP实现方案 【免费下载链接】Unity-URP-Outlines A custom renderer feature for screen space outlines 项目地址: https://gitcode.com/gh_mirrors/un/Unity-URP-Outlines 问题诊断篇&#xff1a;传统描边方案的五大痛点 …...

别再傻傻分不清了!用大白话和Python代码讲透PID控制与阻抗控制的区别(附机器人动力学关联)

从开车到推门&#xff1a;用Python代码拆解PID与阻抗控制的本质差异 想象一下你正在驾驶一辆汽车。当你发现车速低于预期时&#xff0c;会本能地加深油门&#xff1b;而当车速过快时&#xff0c;又会自然松开踏板——这种基于误差不断调整的行为&#xff0c;正是PID控制的朴素体…...

Mac窗口置顶终极指南:用Topit解锁你的多任务超能力 [特殊字符]

Mac窗口置顶终极指南&#xff1a;用Topit解锁你的多任务超能力 &#x1f680; 【免费下载链接】Topit Pin any window to the top of your screen / 在Mac上将你的任何窗口强制置顶 项目地址: https://gitcode.com/gh_mirrors/to/Topit 还在为频繁切换窗口而烦恼&#x…...

[特殊字符]OpenClaw 优化系列(三):基于WSL的OpenClaw备份恢复与文件交互

告别环境崩塌恐惧症&#xff0c;一文掌握WSL下OpenClaw的数据安全与高效操作 Windows下WSL环境准备已经在前面讲了&#xff1a;&#x1f99e; OpenClaw 部署环境准备&#xff1a;Windows下WSL安装及配置全攻略。至于OpenClaw部署&#xff0c;教程已经很多很多了&#xff0c;只…...

PyTorch 2.8镜像新手入门:无需配置,直接开启你的AI项目实战

PyTorch 2.8镜像新手入门&#xff1a;无需配置&#xff0c;直接开启你的AI项目实战 1. 为什么选择PyTorch 2.8预置镜像&#xff1f; 深度学习项目最让人头疼的往往不是算法本身&#xff0c;而是环境配置。不同版本的PyTorch、CUDA、cuDNN之间的兼容性问题&#xff0c;足以让一…...

OpenClaw飞书机器人配置:Qwen3-4B模型对话触发实战

OpenClaw飞书机器人配置&#xff1a;Qwen3-4B模型对话触发实战 1. 为什么选择OpenClaw飞书本地模型组合 去年我接手了一个小团队的内部效率优化项目&#xff0c;需要解决两个核心痛点&#xff1a;一是团队成员频繁在飞书群聊中重复处理相似问题&#xff08;比如数据查询、文档…...