当前位置:网站首页>Go语学习笔记 - Slice、Map | 从零开始Go语言
Go语学习笔记 - Slice、Map | 从零开始Go语言
2022-04-23 06:33:00 【剑客阿良_ALiang】
目录
学习笔记,写到哪是哪。
1、Slice切片
Slice和java中的ArrayList类似,Go语言数组长度不可改变,Slice的长度不固定,可追加元素。
定义方式可以是:
var identifier []type
也可以使用make函数
var slice1 []type = make([]type, len)
样例代码如下
package main
import "fmt"
//切片
func test_slice() {
a := [...]int{1, 2, 3}
b := a[:]
fmt.Printf("a:%T,b%T\na=%v,b=%v\n", a, b, a, b)
c := a[:2]
fmt.Println(c)
s := make([]string, 0)
s = append(s, "haha")
s = append(s, "haha1", "haha2")
fmt.Println(s, len(s), cap(s))
printSlice := func(x []int) { fmt.Printf("len=%d,cap=%d,slice=%v\n", len(x), cap(x), x) }
var d []int
if d == nil {
printSlice(d)
}
copyS := make([]string, cap(s)*2)
copy(copyS, s)
fmt.Println(copyS, s)
}
func main() {
test_slice()
}
执行结果
a:[3]int,b[]int
a=[1 2 3],b=[1 2 3]
[1 2]
[haha haha1 haha2] 3 3
len=0,cap=0,slice=[]
[haha haha1 haha2 ] [haha haha1 haha2]
注意
1、 可以看出a是数组,b是将a数组转为切片。
2、c是a数组的索引为0到2-1的元素,作为切片。
3、可以使用copy函数,进行切片元素拷贝。
4、使用len()、cap()内置函数,可以获取切片的长度以及最大容量。
5、使用append()函数可以对切片元素进行追加。
2、Map
和java中的map类似,在创建map的时候也需要明确键值类型。
定义方式:
var map_variable map[key_data_type]value_data_type
map_variable := make(map[key_data_type]value_data_type)
样例代码如下
package main
import "fmt"
func testMap() {
var a = make(map[string]int)
a["小黄"] = 10
a["小红"] = 18
for s, i := range a {
fmt.Println(s, i)
}
b, ok := a["小兰"]
fmt.Println(b, ok)
a["小花"] = 21
delete(a, "小黄")
fmt.Println(a)
}
func main() {
testMap()
}
执行结果
小黄 10
小红 18
0 false
map[小红:18 小花:21]
注意
1、在获取map某个值的时候,会返回两个返回值,第二个返回值为bool类型,如果不存在该键值对,则为false。
2、可以使用delete()函数进行键值对删除。
小结
使用方式也是相对严谨的,都是在工作中比较常规的数据类型。
版权声明
本文为[剑客阿良_ALiang]所创,转载请带上原文链接,感谢
https://huyi-aliang.blog.csdn.net/article/details/124296403
边栏推荐
猜你喜欢
Protobuf use
C problem of marking the position of polygons surrounded by multiple rectangles
内网渗透系列:内网隧道之dns2tcp
Houdini > rigid body, rigid body breaking RBD
Using lambda expression to solve the problem of C file name sorting (whether it is 100 or 11)
Série de pénétration Intranet: icmpsh du tunnel Intranet
Research on software security based on NLP (2)
Dvwa 靶场练习记录
Buuctf misc brush questions
《内网安全攻防:渗透测试实战指南》读书笔记(五):域内横向移动分析及防御
随机推荐
Houdini>刚体, 刚体破碎RBD
SAP STO With Billing流程与配置
Redis--为什么字符串emstr的字符串长度是44字节上限?
DVWA靶场练习
Feign源码分析
数据库之MySQL——基础篇
A series of articles, a summary of common vulnerabilities of Web penetration (continuously updated)
Attack and defense world misc questions 1-50
VBA调用SAP RFC实现数据读取&写入
第五章 投资性房地产
Ribbon启动流程
Robust and Efficient Quadrotor Trajectory Generation for Fast Autonomous Flight
内网渗透系列:内网隧道之dns2tcp
第七章 资产减值
Chapter V investment real estate
Automatically fit single line text into the target rectangle
Intranet penetration series: dnscat2 of Intranet tunnel
Intranet penetration series: pingtunnel of Intranet tunnel
Dvwa 靶场练习记录
Complete learning from scratch, machine learning and deep learning, including theory and code implementation, mainly using scikit and mxnet, and some practices (on kaggle)