1
0
mirror of https://github.com/vlang/v.git synced 2023-08-10 21:13:21 +03:00

docs: add Array Types section, improve examples (#10357)

This commit is contained in:
Andreas Heissenberger 2021-06-08 19:35:22 +02:00 committed by GitHub
parent 95cf120e2e
commit f0b16fea27
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -622,7 +622,6 @@ println(nums[1]) // `2`
nums[1] = 5
println(nums) // `[1, 5, 3]`
```
#### Array Properties
There are two properties that control the "size" of an array:
* `len`: *length* - the number of defined elements of the array
@ -685,6 +684,70 @@ for i in 0 .. 1000 {
Note: The above code uses a [range `for`](#range-for) statement and a
[push operator (`<<`)](#array-operations).
#### Array Types
An array can be of these types:
| Types | Example Definition |
| ------------ | ------------------------------------ |
| Number | `[]int,[]i64` |
| String | `[]string` |
| Rune | `[]rune` |
| Boolean | `[]bool` |
| Array | `[][]int` |
| Struct | `[]MyStructName` |
| Channel | `[]chan f64` |
| Function | `[]MyFunctionType` `[]fn (int) bool` |
| Interface | `[]MyInterfaceName` |
| Sum Type | `[]MySumTypeName` |
| Generic Type | `[]T` |
| Map | `[]map[string]f64` |
| Enum | `[]MyEnumType` |
| Alias | `[]MyAliasTypeName` |
| Thread | `[]thread int` |
| Reference | `[]&f64` |
| Shared | `[]shared MyStructType` |
**Example Code:**
This example uses [Structs](#structs) and [Sum Types](#sum-types) to create an array
which can handle different types (e.g. Points, Lines) of data elements.
```v
struct Point {
x int
y int
}
struct Line {
p1 Point
p2 Point
}
type ObjectSumType = Line | Point
mut object_list := []ObjectSumType{}
object_list << Point{1, 1}
object_list << Line{
p1: Point{3, 3}
p2: Point{4, 4}
}
dump(object_list)
/*
object_list: [ObjectSumType(Point{
x: 1
y: 1
}), ObjectSumType(Line{
p1: Point{
x: 3
y: 3
}
p2: Point{
x: 4
y: 4
}
})]
*/
```
#### Multidimensional Arrays
@ -1624,6 +1687,10 @@ p = {
y: 4
}
assert p.y == 4
//
// array: first element defines type of array
points := [Point{10, 20}, Point{20, 30}, Point{40, 50}]
println(points) // [Point{x: 10, y: 20}, Point{x: 20, y: 30}, Point{x: 40,y: 50}]
```
Omitting the struct name also works for returning a struct literal or passing one