当前位置: 首页 > 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的有符号十进制整数,左侧用零填充

相关文章:

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

目录标题 一、Variadic Functions1.Syntax2.Examples and understanding how variadic functions work3.Slice arguments vs Variadic arguments 仅改变可变参数4.Gotcha 二、Map1.Create a Map2.Retrieving value for a key from a map3.Checking if a key exists4.Iterate ov…...

JDBC连接数据库如何实现你会吗???

1.首先建立一个maven项目。。。详细过程来了哇 还没有安装maven的童鞋可以看这里&#xff1a;maven的下载安装与配置环境变量&#xff01;&#xff01;&#xff01;&#xff08;全网最详细&#xff09;_明天更新的博客-CSDN博客 有很多小伙伴就有疑问啦&#xff0c;难道我直接…...

C#与C++交互(2)——ANSI、UTF8、Unicode文本编码

【前言】 我们知道计算机上只会存储二进制的数据&#xff0c;无论文本、图片、音频、视频等&#xff0c;当我们将其保存在计算机上时&#xff0c;都会被转成二进制的。我们打开查看的时候&#xff0c;二进制数据又被转成我们看得懂的信息。如何将计算机上的二进制数据转为我们…...

SQLSTATE[42000]: this is incompatible with sql_mode=only_full_group_by in

执行 SELECT *FROM test WHERE id>1 GROUP BY name having AVG(age)>10 ORDER BY id desc limit 1 提示错误 Fatal error: Uncaught PDOException: SQLSTATE[42000]: Syntax error or access violation: 1055 Expression #1 of SELECT list is not in GROUP BY clause…...

企业权限管理(五)-订单分页

订单分页查询 PageHelper介绍 PageHelper是国内非常优秀的一款开源的mybatis分页插件&#xff0c;它支持基本主流与常用的数据库&#xff0c;例如mysql、oracle、mariaDB、DB2、SQLite、Hsqldb等。 PageHelper使用 集成 引入分页插件有下面2种方式&#xff0c;推荐使用 Maven …...

Blender如何给fbx模型添加材质贴图并导出带有材质贴图的模型

推荐&#xff1a;使用 NSDT场景编辑器快速助你搭建可二次编辑的3D应用场景 此教程适合新手用户&#xff0c;专业人士直接可直接绕路。 本教程中介绍了利用Blender建模软件&#xff0c;只需要简单几步就可以为模型添加材质贴&#xff0c;图&#xff0c;并且导出带有材质的模型文…...

MySQL不走索引的情况分析

未建立索引 当数据表没有设计相关索引时&#xff0c;查询会扫描全表。 create table test_temp (test_id int auto_incrementprimary key,field_1 varchar(20) null,field_2 varchar(20) null,field_3 bigint null,create_date date null );expl…...

安装ubuntu22.04系统,配置国内源以及ssh远程登录

一、安装ubuntu22.04系统 原文连接&#xff1a;Ubuntu操作系统22.04版本安装教程-VMware虚拟机_wx63f86e949a470的技术博客_51CTO博客 1.点击界面左侧的开启此虚拟机&#xff0c;即可进入Ubuntu操作系统安装界面&#xff0c;点击​​Try or Install Ubuntu ​​即可开始安装 …...

win10 安装ubuntu子系统并安装宝塔

1、安装子系统 2、ubuntu 中安装宝塔 这里需要注意的&#xff1a; 大部分文章上写的是“面板账户登录信息”不能直接访问&#xff0c;要改成127.0.0.1&#xff1a;8888去访问。 这种情况适合“面板账户登录信息”端口就是8888。 想我的就是32757 这时你就要用 http://127.0.0…...

gazebo 导入从blender导出的dae等文件

背景&#xff1a; gazebo 模型库里的模型在我需要完成的任务中不够用&#xff0c;还是得从 solidworks、3DMax, blender这种建模软件里面在手动画一些&#xff0c;或者去他们的库里面在挖一挖。 目录 1 blender 1-1 blender 相关links 1-2 install 2 gazebo导入模型 2-1 g…...

目标检测YOLOv3基于DarkNet53模型测试-笔记

目标检测YOLOv3基于DarkNet53模型测试-笔记 预测和试测结果&#xff1a; 预测代码如下所示&#xff1a; testInsects.py #YOLOv3网模型测试-单图片文件测试并显示测试结果 import time import os import paddle import numpy as np import cv2 import random from PIL impor…...

Unity项目中查找所有使用某一张图片的材质球,再查找所有使用材质球的预设

废话少说&#xff0c;直接上代码。 using UnityEditor; using UnityEngine;public class FindDependencies : MonoBehaviour {static bool m_bIsSaveFile false;static TextWriteHelper m_szMaterialList new TextWriteHelper();static TextWriteHelper m_szPrefabList new…...

postman接口测试中文汉化教程

想必同学们对于接口测试工具postman的使用并不陌生&#xff0c;以及最近大为流行的国产工具apifox。对于使用过的同学来说&#xff0c;两者区别以及优缺点很容易别展示出来&#xff0c;postman相比apifox来说更加轻量&#xff0c;但是apifox更加符合国人的使用习惯....中国人给…...

java.lang.ClassNotFoundException: com.mysql.cj.jdbc.Driver的解决办法

springcloudAlibaba项目连接mysql时&#xff08;mysql版本8.0.31&#xff0c;Springboot2.2.2,spring cloud Hoxton.SR1,spring cloud alibaba 2.1.0.RELEASE&#xff09;&#xff0c;驱动名称报红&#xff0c;配置如下&#xff1a; 原因&#xff1a;引入的jdbc驱动包和使用的m…...

认识所有权

专栏简介&#xff1a;本专栏作为Rust语言的入门级的文章&#xff0c;目的是为了分享关于Rust语言的编程技巧和知识。对于Rust语言&#xff0c;虽然历史没有C、和python历史悠远&#xff0c;但是它的优点可以说是非常的多&#xff0c;既继承了C运行速度&#xff0c;还拥有了Java…...

恒盛策略:怎样看k线图实图详解如何看懂k线图?

K线图是股票剖析中常用的一种图表&#xff0c;它能够反映一段时间内股票价格的变化状况&#xff0c;对于股票投资者来说非常重要。但是&#xff0c;由于k线图并不是很好理解&#xff0c;很多投资者并不知道怎样看懂它。那么&#xff0c;咱们就从多个视点来看看怎样看k线图实图&…...

物联网的定义、原理、示例、未来

什么是物联网? 物联网 (IoT) 是指由嵌入传感器、软件和网络连接的物理设备、车辆、电器和其他物理对象组成的网络&#xff0c;允许它们收集和共享数据。这些设备(也称为“智能对象”)的范围可以从简单的“智能家居”设备(如智能恒温器)到可穿戴设备(如智能手表和支持RFID的服…...

Vue 整合 Element UI 、路由嵌套和参数传递(五)

一、整合 Element UI 1.1 工程初始化 使用管理员的模式进入 cmd 的命令行模式&#xff0c;创建一个名为 hello-vue 的工程&#xff0c;命令为&#xff1a; # 1、目录切换 cd F:\idea_home\vue# 2、项目的初始化&#xff0c;记得一路的 no vue init webpack hello-vue 1.2 安装…...

Git全栈体系(四)

第七章 IDEA 集成 Git 一、配置 Git 忽略文件 1. Eclipse 特定文件 2. IDEA 特定文件 3. Maven 工程的 target 目录 4. 问题 4.1 为什么要忽略他们&#xff1f; 与项目的实际功能无关&#xff0c;不参与服务器上部署运行。把它们忽略掉能够屏蔽 IDE 工具之间的差异。 4.2 …...

数据结构初阶--二叉树的链式结构

目录 一.二叉树链式结构的概念 二.二叉树链式结构的功能实现 2.1.链式二叉树的定义 2.2.链式二叉树的构建 2.3.链式二叉树的遍历 2.3.1.先序遍历 2.3.2.中序遍历 2.3.3.后序遍历 2.3.4.层序遍历 2.4.链式二叉树的求二叉树的结点数量 法一&#xff1a;计数法 法二&a…...

观成科技:隐蔽隧道工具Ligolo-ng加密流量分析

1.工具介绍 Ligolo-ng是一款由go编写的高效隧道工具&#xff0c;该工具基于TUN接口实现其功能&#xff0c;利用反向TCP/TLS连接建立一条隐蔽的通信信道&#xff0c;支持使用Let’s Encrypt自动生成证书。Ligolo-ng的通信隐蔽性体现在其支持多种连接方式&#xff0c;适应复杂网…...

label-studio的使用教程(导入本地路径)

文章目录 1. 准备环境2. 脚本启动2.1 Windows2.2 Linux 3. 安装label-studio机器学习后端3.1 pip安装(推荐)3.2 GitHub仓库安装 4. 后端配置4.1 yolo环境4.2 引入后端模型4.3 修改脚本4.4 启动后端 5. 标注工程5.1 创建工程5.2 配置图片路径5.3 配置工程类型标签5.4 配置模型5.…...

VB.net复制Ntag213卡写入UID

本示例使用的发卡器&#xff1a;https://item.taobao.com/item.htm?ftt&id615391857885 一、读取旧Ntag卡的UID和数据 Private Sub Button15_Click(sender As Object, e As EventArgs) Handles Button15.Click轻松读卡技术支持:网站:Dim i, j As IntegerDim cardidhex, …...

Java - Mysql数据类型对应

Mysql数据类型java数据类型备注整型INT/INTEGERint / java.lang.Integer–BIGINTlong/java.lang.Long–––浮点型FLOATfloat/java.lang.FloatDOUBLEdouble/java.lang.Double–DECIMAL/NUMERICjava.math.BigDecimal字符串型CHARjava.lang.String固定长度字符串VARCHARjava.lang…...

Python实现prophet 理论及参数优化

文章目录 Prophet理论及模型参数介绍Python代码完整实现prophet 添加外部数据进行模型优化 之前初步学习prophet的时候&#xff0c;写过一篇简单实现&#xff0c;后期随着对该模型的深入研究&#xff0c;本次记录涉及到prophet 的公式以及参数调优&#xff0c;从公式可以更直观…...

Qwen3-Embedding-0.6B深度解析:多语言语义检索的轻量级利器

第一章 引言&#xff1a;语义表示的新时代挑战与Qwen3的破局之路 1.1 文本嵌入的核心价值与技术演进 在人工智能领域&#xff0c;文本嵌入技术如同连接自然语言与机器理解的“神经突触”——它将人类语言转化为计算机可计算的语义向量&#xff0c;支撑着搜索引擎、推荐系统、…...

鱼香ros docker配置镜像报错:https://registry-1.docker.io/v2/

使用鱼香ros一件安装docker时的https://registry-1.docker.io/v2/问题 一键安装指令 wget http://fishros.com/install -O fishros && . fishros出现问题&#xff1a;docker pull 失败 网络不同&#xff0c;需要使用镜像源 按照如下步骤操作 sudo vi /etc/docker/dae…...

使用 SymPy 进行向量和矩阵的高级操作

在科学计算和工程领域&#xff0c;向量和矩阵操作是解决问题的核心技能之一。Python 的 SymPy 库提供了强大的符号计算功能&#xff0c;能够高效地处理向量和矩阵的各种操作。本文将深入探讨如何使用 SymPy 进行向量和矩阵的创建、合并以及维度拓展等操作&#xff0c;并通过具体…...

【7色560页】职场可视化逻辑图高级数据分析PPT模版

7种色调职场工作汇报PPT&#xff0c;橙蓝、黑红、红蓝、蓝橙灰、浅蓝、浅绿、深蓝七种色调模版 【7色560页】职场可视化逻辑图高级数据分析PPT模版&#xff1a;职场可视化逻辑图分析PPT模版https://pan.quark.cn/s/78aeabbd92d1...

【C++特殊工具与技术】优化内存分配(一):C++中的内存分配

目录 一、C 内存的基本概念​ 1.1 内存的物理与逻辑结构​ 1.2 C 程序的内存区域划分​ 二、栈内存分配​ 2.1 栈内存的特点​ 2.2 栈内存分配示例​ 三、堆内存分配​ 3.1 new和delete操作符​ 4.2 内存泄漏与悬空指针问题​ 4.3 new和delete的重载​ 四、智能指针…...