From f0b16fea27843690882e4ec15ba267320c56a835 Mon Sep 17 00:00:00 2001 From: Andreas Heissenberger Date: Tue, 8 Jun 2021 19:35:22 +0200 Subject: [PATCH] docs: add `Array Types` section, improve examples (#10357) --- doc/docs.md | 69 ++++++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 68 insertions(+), 1 deletion(-) diff --git a/doc/docs.md b/doc/docs.md index 79bd4fc837..4e5f56bdda 100644 --- a/doc/docs.md +++ b/doc/docs.md @@ -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