在Go Programming Language书中,作者陈述了以下内容(关于切片的第4.2节):
[切片的长度]是切片元素的数量;它不能超过容量,通常是切片的开始到基础数组的结束之间的元素数。
由于作者选择使用“ 通常”一词,这意味着实际上在某些情况下,切片的容量与切片开始之间的元素数量不同以及底层数组的末尾-何时会出现这种情况?
换句话说,下面的表达式何时为true
:
cap(mySlice) != len(underlyingArray) - startIndexOfSlice
我唯一想到的情况是切片为nil
时,在这种情况下将没有基础数组。
答案 0 :(得分:3)
完整的slice expression可以将容量设置为低于整个基础数组。
<?php
$newCsv = array();
// Get the file in an array
$csv = array_map('str_getcsv', file('a.csv'));
foreach($csv as $row){
//Get the first column
$str = $row[0];
// Split the string
$strParts = explode('#', $str);
$size = sizeof($strParts);
// If it contains #?
if($size > 1){
$newFirstRow = "'location' : '". $strParts[$size -1]."'";
} else{
$newFirstRow = $row[0];
}
array_push($newCsv, array($newFirstRow, $row[1], $row[2]));
}
// Open the file in write mode ('w')
// Remember, this will rewrite the file completely
// If you want to backup the file
// do it before executing this code
$fp = fopen('a.csv', 'w');
// Loop through file pointer and a line
foreach ($newCsv as $fields) {
fputcsv($fp, $fields);
}
fclose($fp);
?>
切片x := make([]string, 20)
y := x[0:10:10]
fmt.Println("x:", len(x), cap(x)) // prints x: 20 20
fmt.Println("y:", len(y), cap(y)) // prints y: 10 10
和x
共享相同的基础数组,但是y
的容量小于y
的容量。