当前位置: 首页 > news >正文

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.lryc.cn/news/119252.html

相关文章:

  • JDBC连接数据库如何实现你会吗???
  • C#与C++交互(2)——ANSI、UTF8、Unicode文本编码
  • SQLSTATE[42000]: this is incompatible with sql_mode=only_full_group_by in
  • 企业权限管理(五)-订单分页
  • Blender如何给fbx模型添加材质贴图并导出带有材质贴图的模型
  • MySQL不走索引的情况分析
  • 安装ubuntu22.04系统,配置国内源以及ssh远程登录
  • win10 安装ubuntu子系统并安装宝塔
  • gazebo 导入从blender导出的dae等文件
  • 目标检测YOLOv3基于DarkNet53模型测试-笔记
  • Unity项目中查找所有使用某一张图片的材质球,再查找所有使用材质球的预设
  • postman接口测试中文汉化教程
  • java.lang.ClassNotFoundException: com.mysql.cj.jdbc.Driver的解决办法
  • 认识所有权
  • 恒盛策略:怎样看k线图实图详解如何看懂k线图?
  • 物联网的定义、原理、示例、未来
  • Vue 整合 Element UI 、路由嵌套和参数传递(五)
  • Git全栈体系(四)
  • 数据结构初阶--二叉树的链式结构
  • Taro UI中的AtTabs
  • ChatGPT FAQ指南
  • 在矩池云使用ChatGLM-6B ChatGLM2-6B
  • 7.2 手撕VGG11模型 使用Fashion_mnist数据训练VGG
  • docker安装ES
  • python爬虫实战(2)--爬取某博热搜数据
  • k8s的Namespace详解
  • 【Redis】Redis内存过期策略和内存淘汰策略
  • 技术干货 | cilium 原理之sock_connect
  • K8S之Pod详解与进阶
  • 【小曾同学赠书活动】开始啦—〖测试设计思想〗