移除元素
如果要从切片中移除元素,下面是一个比较简单粗暴的写法
slice := []int{1, 2, 3, 4, 5}
// 移除第三个 element
slice = append(slice[0:2], slice[3:5]...)
if !(len(slice) == 4) {
log.Fatal("Wrong length")
}
}
这种写法的条件是知道要删 『第几个 element』 时才能写
golang 并没有移除元素的方法,上述只是从中截断,再重组
可以用 struct 当作 element ,在 slice 中存更多样的资料
通常在宣告一个空 slice 时 ,该 slice 是没有 len 的
x:=[]string{}
x[0] = "1"
上述写法会导致 panic
panic: runtime error: index out of range [0] with length 0
请使用 append 方法
x := []string{}
x = append(x, "1")
只能 append 同资料型态的变数/struct
golang 的 map 指的并不是地图
而是一组可以自定义 key 的 key/value 资料组合
google 了半天我还是没找到一个公认的 map 标准用中文名称
只查到很多概念类似、或是有人使用的名词、而且大部分来自对岸QQ
「映射」「哈希」 「集合」 「关连性阵列」 ... etc
make map
建一个 key & value 型态皆为 string 的 map
m := make(map[string]string)
m["Python"] = "Django"
m["JavaScript"] = "Angular"
m["Go"] = "Beego"
m["PHP"] = "Laravel"
for k,v:= range m {
fmt.Println(k,v)
}
}
check 是否存在这个 key
如果键/值对不存在,会依 map 的值 的型别回传预设值
m := make(map[string]string)
m["Go"] = "Beego"
m["Python"] = "Django"
m["Ruby"] = "Rails"
m["PHP"] = "Laravel"
fmt.Println(m["Java"])
if m["Java"]=="" {
fmt.Println("真的是空的")
}
}
因为根本没有 Java 这个 key,所以 m["Java"] 会依原本宣告的 value 格式给预设值
about 预设值
When storage is allocated for a variable, either through a declaration or a call of new, or when a new value is created, either through a composite literal or a call of make, and no explicit initialization is provided, the variable or value is given a default value. Each element of such a variable or value is set to the zero value for its type: false for booleans, 0 for numeric types, "" for strings, and nil for pointers, functions, interfaces, slices, channels, and maps. This initialization is done recursively, so for instance each element of an array of structs will have its fields zeroed if no value is specified.
https://golang.org/ref/spec#The_zero_value
false for booleans
0 for numeric
"" for strings
nil for pointers, functions, interfaces, slices, channels, and maps
如果不确定 key 是否存在,可以用 ok 来做检查
m := make(map[string]string)
m["Go"] = "Beego"
m["Python"] = "Django"
m["Ruby"] = "Rails"
m["PHP"] = "Laravel"
v, ok := m["Go"]
fmt.Println(v, ok)
}
ok 可以自己定义要用什麽字眼,上面的 ok 是一个 bool ,如果 m["Go"] 存在回 true,如果不存在回 false
map vs slice
两者皆为 go 中重要的变数型态
Slice:
Slice 是 base on array 的一种资料型态。
Slice 主要功能在於其扩充性 以及 append 方法。
Slice 拥有一个指向开始位置的「pointer ptr」、「长度 len」、「最大容量 cap」。
Slice 可以依需求增长或收缩。Slice 的增长通常包括为内存的重新分配。像 copy 和 append 这样的 func 可以帮助我增加 slice 的长度。
Map:
golang 常用於 web 的後端,那麽在彼此跟彼此之间沟通时常常会用到 json 格式,json 格式跟 map 的相性非常非常的契合
储存 key 可以为非 int (比方说: string) 的 slice
map 可以自定义 key 则提供了许多不同的使用方式
Q1. 什麽是 SVN ? Subversion (简称SVN),与 Git 一样是原始码版本管理软...
可能要完赛了就有种懈怠感呢 但之後还是会继续修改文章、有新的学习也会整理上来。 虽然这系列是学习记...
Purpose: Set the Queue to switch Queue 0 : Max ra...
到底 PM 在做什麽? 以前还没有开始当产品经理前,因为对这个职位很有兴趣希望能够往这个职涯发展,...
早期还在当工程师的时候,每次碰到一些自己没兴趣,或者自己的价值判断觉得不合理的东西,就会下意识的亮出...