Go语言基础: 有参函数Func、Map、Strings详细案例教程

目录标题

  • 一、Variadic Functions
    • 1.Syntax
    • 2.Examples and understanding how variadic functions work
    • 3.Slice arguments vs Variadic arguments 仅改变可变参数
    • 4.Gotcha
  • 二、Map
    • 1.Create a Map
    • 2.Retrieving value for a key from a map
    • 3.Checking if a key exists
    • 4.Iterate over all elements in a map
    • 5. Deleting items from a map
    • 6.Map of structs
    • 7.Length of the map
    • 8.Maps are reference types
    • 9.Maps equality
  • 三、Strings
    • 1.Accessing individual bytes of a string
    • 2.Accessing individual characters of a string
    • 3.String length
    • 4.String comparison
    • 5.String concatenation
    • 6.Strings are immutable
  • 四、Printf的%格式化字符串

一、Variadic Functions

1.Syntax

	package mainimport ("fmt")func Hello(a int, b ...int) {fmt.Println(a, b)		// 666 [22 333 555]}func main() {Hello(666, 22, 333, 555)}

2.Examples and understanding how variadic functions work

	func find(num int, nums ...int) { // 设置一个目标数字与一个 Arrays 查看当前目标数字是否在arrays里面fmt.Printf("type of nums is %T\n", nums)found := falsefor i, v := range nums { // 循环 Arraysif v == num { // 如果值等于 numfmt.Println(num, "found at index", i, "in", nums)found = true}}if !found {fmt.Println(num, "not find in ", nums)}fmt.Printf("\n")}func main() {find(89, 87, 90, 88, 89)		find(45, 56, 67, 45, 90, 109)find(78, 38, 56, 98)find(87)}// type of nums is []int// 89 found at index 3 in [87 90 88 89]// 还可以这样调用nums := []int{89, 90, 95}find(89, nums) // 如果这样调用则报错 无法运行 需要添加 ...   .\variadic functions. go:33:11: cannot use nums (variable of type []int) as int value in argument to findfind(89, nums...)	// 89 found at index 0 in [89 90 95]

3.Slice arguments vs Variadic arguments 仅改变可变参数

	func find(num int, nums []int) { // 设置一个目标数字与一个 Arrays 查看当前目标数字是否在arrays里面fmt.Printf("type of nums is %T\n", nums)found := falsefor i, v := range nums { // 循环 Arraysif v == num { // 如果值等于 numfmt.Println(num, "found at index", i, "in", nums)found = true}}if !found {fmt.Println(num, "not find in ", nums)}fmt.Printf("\n")}func main() {find(89, []int{87, 90, 88, 89})find(45, []int{56, 67, 45, 90, 109})find(78, []int{38, 56, 98})find(87, []int{})}

4.Gotcha

	package mainimport (  "fmt")func change(s ...string) {s[0] = "Go"s = append(s, "playground") // append会创建一个新的切片fmt.Println(s)              // [Go world playground]}func main() {welcome := []string{"hello", "world"}change(welcome...)   // change没有受到添加playground的影响 所以它的容量还是2(change操作的是原始的切片, 如果原始切片满了则会创建一个新的切片)fmt.Println(welcome) // 所以输出的是 Go world}// [Go world playground]// [Go world]// Go中的append原始切片如果没有满 则会使用原始切片不会创建新的切片 如果满了则会创建一个新的切片

二、Map

1.Create a Map

	package mainimport "fmt"// create a mapfunc main() {// example 1employeeSalary := make(map[string]int)fmt.Println(employeeSalary)// example 2Department := map[string]string{"Designer": "设计部","Research": "研发部",}fmt.Println(Department)// add items to mapemployeeSalary["Like"] = 15000employeeSalary["Jack"] = 9000employeeSalary["Lisa"] = 10000fmt.Println("employeeSalary map contents:", employeeSalary)var employeeSalary map[string]intfmt.Println(employeeSalary)employeeSalary["Like"] = 15000 	// 不可行 	panic: assignment to entry in nil map}

2.Retrieving value for a key from a map

	employeeSalary := map[string]int{"steve": 12000,"jamie": 15000,"mike":  9000,}employee := "jamie"salary := employeeSalary[employee]fmt.Println("Salary of", employee, "is", salary)		// Salary of jamie is 15000fmt.Println("Salary of mike is", employeeSalary["mike"])	// Salary of mike is 9000fmt.Println("Salary of joe is", employeeSalary["joe"])	 // Salary of joe is 0 没有则为0

3.Checking if a key exists

	employeeSalary := map[string]int{"steve": 12000,"jamie": 15000,"mike":  9000,}newEmp := "jamie"value, ok := employeeSalary[newEmp] // 0 falsefmt.Println(value, ok)if ok == true {fmt.Println(ok)                               // truefmt.Println("Salary of", newEmp, "is", value) // Salary of jamie is 15000return}fmt.Println(newEmp, "not Found")

4.Iterate over all elements in a map

	employeeSalary := map[string]int{"steve": 12000,"jamie": 15000,"mike":  9000,}fmt.Println("Contents of the map")for key, value := range employeeSalary {fmt.Printf("employessSalary[%s] = %d\n", key, value)}// 输出// Contents of the map//employessSalary[steve] = 12000//employessSalary[jamie] = 15000//employessSalary[mike] = 9000

5. Deleting items from a map

	employeeSalary := map[string]int{"steve": 12000,"jamie": 15000,"mike":  9000,}fmt.Println("Contents of the map")for key, value := range employeeSalary {fmt.Printf("employessSalary[%s] = %d\n", key, value)}// 输出// Contents of the map//employessSalary[steve] = 12000//employessSalary[jamie] = 15000//employessSalary[mike] = 9000

6.Map of structs

	package mainimport (  "fmt")type employee struct {  salary  intcountry string}func main() {  emp1 := employee{salary: 6666, country: "Usa"}emp2 := employee{salary: 7777, country: "Canada"}emp3 := employee{salary: 8888, country: "China"}employeeInfo := map[string]employee{"Steve": emp1,"Lisa":  emp2,"Like":  emp3,}for name, info := range employeeInfo {fmt.Printf("Employee: %s Salary:$%d  Country: %s\n", name, info.salary, info.country)}}// Employee: Lisa Salary:$7777  Country: Canada// Employee: Like Salary:$8888  Country: China// Employee: Steve Salary:$6666  Country: Usa

7.Length of the map

	emp1 := employee{salary: 6666, country: "Usa"}emp2 := employee{salary: 7777, country: "Canada"}emp3 := employee{salary: 8888, country: "China"}employeeInfo := map[string]employee{"Steve": emp1,"Lisa":  emp2,"Like":  emp3,}fmt.Println("length is", len(employeeInfo))// length is 3

8.Maps are reference types

	employeeSalary := map[string]int{"steve": 12000,"jamie": 15000,"mike":  9000,}fmt.Println("Original employee salary", employeeSalary)modified := employeeSalarymodified["mike"] = 18000fmt.Println("Employee salary changed", employeeSalary)// Original employee salary map[jamie:15000 mike:9000 steve:12000]// Employee salary changed map[jamie:15000 mike:18000 steve:12000]	

9.Maps equality

	package mainfunc main() {  map1 := map[string]int{"one": 1,"two": 2,}map2 := map1if map1 == map2 {}}// 不能使用 == 比较 只能判断是否为空

三、Strings

1.Accessing individual bytes of a string

	package mainimport "fmt"func printBytes(s string) {fmt.Printf("Bytes:") // 注意go语言不会自动换行for i := 0; i < len(s); i++ {fmt.Printf("%x ", s[i])}}func main() {name := "Hello World"fmt.Printf("String: %s\n", name)printBytes(name)}//	String: Hello World//	Bytes:48 65 6c 6c 6f 20 57 6f 72 6c 64

2.Accessing individual characters of a string

	package mainimport "fmt"func printBytes(s string) {fmt.Printf("Bytes:") // 注意go语言不会自动换行for i := 0; i < len(s); i++ {fmt.Printf("%x ", s[i])}}func printChars(s string) {fmt.Printf("Characters: ")runes := []rune(s) // 字符串被转换为一片符文for i := 0; i < len(runes); i++ {fmt.Printf("%c", runes[i]) // Characters: Hello World}}func main() {name := "Hello World"fmt.Printf("String: %s\n", name)printChars(name)fmt.Printf("\n")printBytes(name)fmt.Printf("\n\n")name = "Señor" // 特殊字符 如果不转换 则不一致	S e à ± o rfmt.Printf("String: %s\n", name)printChars(name)fmt.Printf("\n")printBytes(name)}// String: Hello World// Characters: Hello World// Bytes:48 65 6c 6c 6f 20 57 6f 72 6c 64// String: Señor// Characters: Señor// Bytes:53 65 c3 b1 6f 72

3.String length

	word1 := "Señor"fmt.Printf("String: %s\n", word1)fmt.Printf("Length: %d\n", utf8.RuneCountInString(word1)) // 返回字符数量fmt.Printf("Number of bytes: %d\n", len(word1))           // 获取当前字符串长度 	ñ 表示两个fmt.Printf("\n")word2 := "Pets"fmt.Printf("String: %s\n", word2)fmt.Printf("Length: %d\n", utf8.RuneCountInString(word2))fmt.Printf("Number of bytes: %d\n", len(word2))

4.String comparison

	func compareStrings(str1 string, str2 string) {if str1 == str2 {fmt.Printf("%s and %s are equal\n", str1, str2)return}fmt.Printf("%s and %s are not equal\n", str1, str2)}string1 := "Go"string2 := "Go"compareStrings(string1, string2)string3 := "hello"string4 := "world"compareStrings(string3, string4)// Go and Go are equal// hello and world are not equal

5.String concatenation

	string1 := "Go"string2 := "is awesome"//result := string1 + " " + string2result := fmt.Sprintf("%s %s", string1, string2)fmt.Println(result)// Go is awesome

6.Strings are immutable

	func mutate(s string)string {  s[0] = 'a'	//any valid unicode character within single quote is a rune return s}func main() {  h := "hello"fmt.Println(mutate(h))		}// 输出 cannot assign to s[0] (value of type byte)// 优化func mutate(s []rune) string {  	// mutate函数接受一个[]rune类型的切片作为参数,并返回一个字符串。s[0] = 'a' 					  // []rune是一个Unicode字符的切片类型。它将字符串转换为Unicode字符切片,以便我们可以修改字符串中的字符。return string(s)}func main() {  h := "hello"fmt.Println(mutate([]rune(h)))	// mutate函数修改了切片中的第一个字符,将其替换为'a'。}

四、Printf的%格式化字符串

	%d: 表示有符号十进制整数(int类型)%f: 表示浮点数(float32float64类型)%s: 表示字符串%t: 表示布尔值(truefalse%c: 表示字符(按Unicode码点输出)%p: 表示指针地址%v: 表示通用的值(以默认方式格式化)%+v: 表示结构体值(包含字段名)%#v: 表示值的Go语法表示形式%x: 表示以十六进制格式输出整数或字节切片%b: 表示以二进制格式输出整数%o: 表示以八进制格式输出整数%e 或 %E: 表示科学计数法表示的浮点数%t: 表示以字符串形式输出时间(time.Time类型)%T: 表示值的类型(类型的完全规格)%10d: 表示输出宽度为10的有符号十进制整数%.2f: 表示输出带有两位小数的浮点数%05d: 表示输出宽度为5的有符号十进制整数,左侧用零填充

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/29477.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

【solon生态】- solon.cloud.micrometer插件使用指南及micrometer详解

solon.cloud.micrometer插件使用指南 solon是什么solon的cloud生态图快速入门 micrometer指南micrometer是什么监控系统 Supported Monitoring Systems注册表 Registry度量 Meters度量名 Naming Meters度量标签 Tag Naming通用标签 Common Tags 指标过滤器 MeterFilter聚合速率…

农业大数据可视化平台,让农业数据更直观展现!

农业大数据可视化平台是指利用大数据技术和可视化工具&#xff0c;对农业领域的数据进行收集、整理、分析和展示的平台。它可以帮助农业从业者更好地理解和利用农业数据&#xff0c;提高农业生产效率和决策水平。 农业大数据可视化平台通常具有以下特点和功能&#xff1a; 数据…

【JAVA】七大排序算法(图解)

稳定性&#xff1a; 待排序的序列中若存在值相同的元素&#xff0c;经过排序之后&#xff0c;相等元素的先后顺序不发生改变&#xff0c;称为排序的稳定性。 思维导图&#xff1a; &#xff08;排序名称后面蓝色字体为时间复杂度和稳定性&#xff09; 1.直接插入排序 核心思…

中通快递:短期财务前景良好,长期财务业绩将遭受严重打击

来源&#xff1a;猛兽财经 作者&#xff1a;猛兽财经 华尔街分析师对中通快递的短期财务前景预测 华尔街分析师目前预测中通快递&#xff08;ZTO&#xff09;将在2023财年全年产生一份相当不错的财务业绩。 根据S&P Capital IQ的数据&#xff0c;在过去的6个月里&#xff…

记一次Linux启动Mysql异常解决

文章目录 第一步&#xff1a; netstat -ntlp 查看端口情况2、启动Mysql3、查看MySQL日志 tail -100f /var/log/mysqld.log4、查看磁盘占用情况&#xff1a;df -h5、思路小结 第一步&#xff1a; netstat -ntlp 查看端口情况 并没有发现3306数据库端口 2、启动Mysql service …

Java # List

ArrayList<>() import java.util.ArrayList; // 引入 ArrayList 类ArrayList<E> objectName new ArrayList<>();  // 初始化 常用方法 方法描述add()将元素插入到指定位置的 arraylist 中addAll()添加集合中的所有元素到 arraylist 中clear()删除 arrayl…

测试经典书籍拆分讲解

一、全程软件测试 测试行业的经典书籍 测试方法测试策略领域测试主流测试技术涵盖了软件测试的流程与方法体系 二、探索式测试 探索式测试的经典代表性书籍探索式测试是业务测试和手工测试实践中的一个方法论 三、Google测试之道 高级测试工程师与架构师必读讲解google的测…

R语言中的函数24:Combinat:combn(), permn()

介绍 combinat中的combn()和permn()函数可以得到所有的排列组合的情况 combn()函数 combn(x, m, funNULL, simplifyTRUE, …)x – 组合的向量源m – 要取的元素的数量fun – 应用于每个组合的函数(可能为空)simplify – 逻辑的&#xff0c;如果是FALSE&#xff0c;返回一个列…

Spring学习笔记——2

Spring学习笔记——2 1、Bean的基本注解开发1.1、注解版本和Component简介1.2、Component使用1.3、Component的三个衍生注解 二、Bean依赖注入注解开发2.1、依赖注入相关注解2.2、Autowired扩展 三、非自定义Bean注解开发四、Bean配置类的注解开发五、Spring注解的解析原理六、…

LeetCode_动态规划_中等_1749.任意子数组和的绝对值的最大值

目录 1.题目2.思路3.代码实现&#xff08;Java&#xff09; 1.题目 给你一个整数数组 nums 。一个子数组 [numsl, numsl1, …, numsr-1, numsr] 的 和的绝对值 为 abs(numsl numsl1 … numsr-1 numsr) 。请你找出 nums 中和的绝对值 最大的任意子数组&#xff08;可能为空…

数学建模-爬虫系统学习

尚硅谷Python爬虫教程小白零基础速通&#xff08;含python基础爬虫案例&#xff09; 内容包括&#xff1a;Python基础、Urllib、解析&#xff08;xpath、jsonpath、beautiful&#xff09;、requests、selenium、Scrapy框架 python基础 进阶&#xff08;字符串 列表 元组 字典…

Java——基础语法(二)

前言 「作者主页」&#xff1a;雪碧有白泡泡 「个人网站」&#xff1a;雪碧的个人网站 「推荐专栏」&#xff1a; ★java一站式服务 ★ ★ React从入门到精通★ ★前端炫酷代码分享 ★ ★ 从0到英雄&#xff0c;vue成神之路★ ★ uniapp-从构建到提升★ ★ 从0到英雄&#xff…

stm32 cubemx ps2无线(有线)手柄

文章目录 前言一、cubemx配置二、代码1.引入库bsp_hal_ps2.cbsp_hal_ps2.h 2.主函数 前言 本文讲解使用cubemx配置PS2手柄实现对手柄的按键和模拟值的读取。 很简单&#xff0c;库已经封装好了&#xff0c;直接就可以了。 文件 一、cubemx配置 这个很简单&#xff0c;不需要…

Flutter iOS 与 flutter 相互通信

在混合开发中避免不了通信&#xff0c;简单记录一下&#xff0c;Flutter iOS工程与Flutter 之间相互通信。 Flutter中通过Platform Channel实现Flutter和原生端的数据传递&#xff0c;是怎么进行数据通信&#xff0c;以及怎么配置&#xff0c;下面一一进行详解。 FlutterMetho…

图的拓扑排序算法

拓扑排序 什么是拓扑排序&#xff1f; 比如说&#xff0c;我们平时工作过程中一定听过一个词叫做—不能循环依赖。什么意思&#xff1f; A依赖BCD&#xff0c;B依赖CD&#xff0c;C依赖D&#xff0c;D依赖EF&#xff0c;想要获得A的话&#xff0c;首先就要先有EF&#xff0c;有…

ArcGIS制作带蒙版的遥感影像地图

这次文章我们来介绍一下&#xff0c;如何通过一个系统的步骤完成ArcGIS制作带蒙版的遥感影像地图。 主要的步骤包括&#xff1a; 1 添加行政区划数据 2 导出兴趣去乡镇矢量范围 3 添加遥感影像底图 4 制作蒙版 5 利用自动完成面制作蒙版 6 标注乡镇带晕渲文字 7 …

Linux面试专题

Linux面试专题 1 Linux中主要有哪几种内核锁?2 Linux 中的用户模式和内核模式是什么含意?3 怎样申请大块内核内存?4用户进程间通信主要哪几种方式?5通过伙伴系统申请内核内存的函数有哪些?6) Linux 虚拟文件系统的关键数据结构有哪些?(至少写出四个)7) 对文件或设备的操作…

个推数据驱动运营增长城市巡回沙龙首发北京站

如今很多互联网企业正在加速数智化升级&#xff0c;希望通过运用数据以实现降本提效和运营增长。为帮助更多伙伴在工作中“用好”数据&#xff0c;提升运营效率与效果&#xff1b;同时和更多对用户运营感兴趣的伙伴&#xff0c;共创、共享数智运营实践成果&#xff0c;个推重磅…

设计模式行为型——访问者模式

目录 访问者模式的定义 访问者模式的实现 访问者模式角色 访问者模式类图 访问者模式举例 访问者模式代码实现 访问者模式的特点 优点 缺点 使用场景 注意事项 实际应用 访问者模式的定义 访问者模式&#xff08;Visitor Pattern&#xff09;属于行为型设计模式&am…

【JAVA开发工具系列】Git

Git常用功能整理 1.自动打包1.1 第一步安装git 服务1.1.1 查看版本1.1.2 安装1.1.3 配置秘钥 1.2 第二步 配置maven1.2.1 下载1.2.2解压1.2.3 配置环境变量1.2.4刷新环境变量文件1.2.5测试环境1.2.6 修改数据源 1.3 部署项目1.3.1拉取项目 1.4 jar 重启tomcat 2.SmartGit合并主…