From 9f6e4a86e907e0cbf07890e0446a6153a6389265 Mon Sep 17 00:00:00 2001 From: Nick Treleaven Date: Sun, 26 Jul 2020 19:29:51 +0100 Subject: [PATCH] doc: improve array docs (#5950) --- doc/docs.md | 30 ++++++++++++++---------------- 1 file changed, 14 insertions(+), 16 deletions(-) diff --git a/doc/docs.md b/doc/docs.md index b9d3c9a7c0..fd91b9038e 100644 --- a/doc/docs.md +++ b/doc/docs.md @@ -446,23 +446,21 @@ println(nums.len) // "0" // Declare an empty array: users := []int{} - -// We can also preallocate a certain amount of elements. -ids := []int{ len: 50, init: 0 } // This creates an array with 50 zeros ``` The type of an array is determined by the first element: * `[1, 2, 3]` is an array of ints (`[]int`). * `['a', 'b']` is an array of strings (`[]string`). -If V is unable to infer the type of an array, the user can explicitly specify it for the first element: `[byte(0x0E), 0x1F, 0xBA, 0x0E]` - +If V is unable to infer the type of an array, the user can explicitly specify it for the first element: `[byte(16), 32, 64, 128]`. V arrays are homogeneous (all elements must have the same type). This means that code like `[1, 'a']` will not compile. -`.len` field returns the length of the array. Note that it's a read-only field, +The `.len` field returns the length of the array. Note that it's a read-only field, and it can't be modified by the user. Exported fields are read-only by default in V. See [Access modifiers](#access-modifiers). +#### Array operations + ```v mut nums := [1, 2, 3] nums << 4 @@ -485,26 +483,26 @@ It can also append an entire array. `val in array` returns true if the array contains `val`. See [`in` operator](#in-operator). -  +#### Initializing array properties During initialization you can specify the capacity of the array (`cap`), its initial length (`len`), -and the default element (`init`). +and the default element (`init`): -Setting the capacity improves performance of insertions, as it reduces the amount of reallocations in -dynamic arrays: +```v +arr := []int{ len: 5, init: -1 } // `[-1, -1, -1, -1, -1]` +``` + +Setting the capacity improves performance of insertions, as it reduces the number of reallocations needed: ```v mut numbers := []int{ cap: 1000 } -// Now able to add new elements without reallocating +println(numbers.len) // 0 +// Now appending elements won't reallocate for i in 0 .. 1000 { numbers << i - // same as - // numbers[i] = i } ``` - -`[]int{ len: 5, init: -1 }` will create `[-1, -1, -1, -1, -1]`. - +Note: The above code uses a [range `for`](#range-for) statement. #### Array methods