Go语言的slice

以下摘自The Go Programming Language

A slice has three components: a pointer, a length, and a capacity. The pointer points to the first element of the array that is reachable through the slice, which is not necessarily the array’s first element. The length is the number of slice elements; it can’t exceed the capacity, which is usually the number of elements between the start of the slice and the end of the underlying array. The built-in functions len and cap return those values.Multiple slices can share the same underlying array and may refer to overlapping parts of that array:

 

Untitled

The slice operator s[i:j], where 0 ≤ i ≤ j ≤ cap(s), creates a new slice that refers to elements i through j-1 of the sequence s, which may be an array variable, a pointer to an array, or another slice. The resulting slice has j-i elements. If i is omitted, it’s 0, and if j is omitted, it’s len(s).

 

Since a slice contains a pointer to an element of an array, passing a slice to a function permits the function to modify the underlying array elements. In other words, copying a slice creates an alias for the underlying array.

 

Unlike arrays, slices are not comparable, so we cannot use == to test whether two slices contain the same elements. The standard library provides the highly optimized bytes.Equal function for comparing two slices of bytes ([]byte), but for other types of slice, we must do the comparison ourselves.

 

The only legal slice comparison is against nil, as in
if summer == nil { /* … */ }
The zero value of a slice type is nil. A nil slice has no underlying array. The nil slice has length and capacity zero, but there are also non-nil slices of length and capacity zero, such as []int{} or make([]int, 3)[3:]. As with any type that can have nil values, the nil value of a particular slice type can be written using a conversion expression such as []int(nil).

var s []int // len(s) == 0, s == nil

s = nil // len(s) == 0, s == nil

s = []int(nil) // len(s) == 0, s == nil

s = []int{} // len(s) == 0, s != nil

So, if you need to test whether a slice is empty, use len(s) == 0, not s == nil. Other than comparing equal to nil, a nil slice behaves like any other zero-length slice.

 

/proc/self/mountinfo文件

Linux系统的/proc/self/mountinfo记录当前系统所有挂载文件系统的信息:

# cat /proc/self/mountinfo
17 61 0:16 / /sys rw,nosuid,nodev,noexec,relatime shared:6 - sysfs sysfs rw,seclabel
18 61 0:3 / /proc rw,nosuid,nodev,noexec,relatime shared:5 - proc proc rw
19 61 0:5 / /dev rw,nosuid shared:2 - devtmpfs devtmpfs rw,seclabel,size=6024144k,nr_inodes=1506036,mode=755
......

关于这个文件各个字段的解释,可以参考这里Linux系统df命令的实现也会读取这个文件,比如获得文件系统类型:

# df -h
Filesystem             Size  Used Avail Use% Mounted on
/dev/mapper/rhel-root   50G   44G  6.5G  88% /
devtmpfs               5.8G     0  5.8G   0% /dev
tmpfs                  5.8G   84K  5.8G   1% /dev/shm
......