Skip to content

Commit

Permalink
Updated section regarding enums (FuelLabs#1854)
Browse files Browse the repository at this point in the history
* Moved code into /sway/examples/ and reworked entire page for structs, tuples and enums
  • Loading branch information
Braqzen authored Jun 6, 2022
1 parent a34b4b9 commit 8e07f9a
Show file tree
Hide file tree
Showing 22 changed files with 320 additions and 142 deletions.
2 changes: 1 addition & 1 deletion docs/src/SUMMARY.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@
- [Built-in Types](./basics/built_in_types.md)
- [Blockchain Types](./basics/blockchain_types.md)
- [Functions](./basics/functions.md)
- [Structs and Tuples](./basics/structs_and_tuples.md)
- [Structs, Tuples, and Enums](./basics/structs_tuples_and_enums.md)
- [Methods and Associated Functions](./basics/methods_and_associated_functions.md)
- [Comments and Logging](./basics/comments_and_logging.md)
- [Control Flow](./basics/control_flow.md)
Expand Down
2 changes: 1 addition & 1 deletion docs/src/basics/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ Sway basics.
- [Built-in Types](./built_in_types.md)
- [Blockchain Types](./blockchain_types.md)
- [Functions](./functions.md)
- [Structs and Tuples](./structs_and_tuples.md)
- [Structs, Tuples, and Enums](./structs_tuples_and_enums.md)
- [Methods and Associated Functions](./methods_and_associated_functions.md)
- [Control Flow](./control_flow.mdz)
- [Comments and Logging](./comments_and_logging.md)
140 changes: 0 additions & 140 deletions docs/src/basics/structs_and_tuples.md

This file was deleted.

102 changes: 102 additions & 0 deletions docs/src/basics/structs_tuples_and_enums.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
# Structs, Tuples, and Enums

## Structs

Structs in Sway are a named grouping of types. You may also be familiar with structs via another name: _product types_. Sway does not make any significantly unique usages of structs; they are similar to most other languages which have structs. If you're coming from an object-oriented background, a struct is like the data attributes of an object.

Firstly, we declare a struct named `Foo` with two fields. The first field is named `bar` and it accepts values of type `u64`, the second field is named `baz` and it accepts `bool` values.

```sway
{{#include ../../../examples/structs/src/data_structures.sw}}
```

In order to instantiate the struct we use _struct instantiation syntax_, which is very similar to the declaration syntax except with expressions in place of types.

There are three ways to instantiate the struct.

- Hardcoding values for the fields
- Passing in variables with names different than the struct fields
- Using a shorthand notation via variables that are the same as the field names

```sway
{{#include ../../../examples/structs/src/main.sw}}
```

> **Note**
> You can mix and match all 3 ways to instantiate the struct at the same time.
> Moreover, the order of the fields does not matter when instantiating however we encourage declaring the fields in alphabetical order and instantiating them in the same alphabetical order
### Struct Memory Layout

> **Note**
> This information is not vital if you are new to the language, or programming in general
Structs have zero memory overhead. What that means is that in memory, each struct field is laid out sequentially. No metadata regarding the struct's name or other properties is preserved at runtime. In other words, structs are compile-time constructs. This is the same in Rust, but different in other languages with runtimes like Java.

## Tuples

Tuples are a [basic static-length type](./built_in_types.md#tuple-types) which contain multiple different types within themselves. The type of a tuple is defined by the types of the values within it, and a tuple can contain basic types as well as structs and enums.

You can access values directly by using the `.` syntax. Moreover, multiple variables can be extracted from a tuple using the destructuring syntax.

```sway
{{#include ../../../examples/tuples/src/main.sw}}
```

## Enums

_Enumerations_, or _enums_, are also known as _sum types_. An enum is a type that could be one of several variants. To declare an enum, you enumerate all potential variants.

Here, we have defined five potential colors. Each enum variant is just the color name. As there is no extra data associated with each variant, we say that each variant is of type `()`, or unit.

> **Note**
> enum instantiation does not require the `~` tilde syntax
```sway
{{#include ../../../examples/enums/src/basic_enum.sw}}
```

### Enums of Structs

It is also possible to have an enum variant contain extra data. Take a look at this more substantial example, which combines struct declarations with enum variants:

```sway
{{#include ../../../examples/enums/src/enum_of_structs.sw}}
```

### Enums of Enums

It is possible to define enums of enums:

```sway
{{#include ../../../examples/enums/src/enum_of_enums.sw}}
```

#### Preferred usage

The preferred way to use enums is to use the individual (not nested) enums directly because they are easy to follow and the lines are short:

```sway
{{#include ../../../examples/enums/src/enums_preferred.sw}}
```

#### Inadvisable

If you wish to use the nested form of enums via the `Error` enum from the example above, then you can instantiate them into variables using the following syntax:

```sway
{{#include ../../../examples/enums/src/enums_avoid.sw}}
```

Key points to note:

- You must import all of the enums you need instead of just the `Error` enum
- The lines may get unnecessarily long (depending on the names)
- The syntax is not the most ergonomic

### Enum Memory Layout

> **Note**
> This information is not vital if you are new to the language, or programming in general.
Enums do have some memory overhead. To know which variant is being represented, Sway stores a one-word (8-byte) tag for the enum variant. The space reserved after the tag is equivalent to the size of the _largest_ enum variant. So, to calculate the size of an enum in memory, add 8 bytes to the size of the largest variant. For example, in the case of `Color` above, where the variants are all `()`, the size would be 8 bytes since the size of the largest variant is 0 bytes.
2 changes: 2 additions & 0 deletions examples/enums/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
out
target
12 changes: 12 additions & 0 deletions examples/enums/Forc.lock
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
[[package]]
name = 'core'
dependencies = []

[[package]]
name = 'enums'
dependencies = []

[[package]]
name = 'std'
source = 'git+https://github.com/fuellabs/sway?tag=v0.14.5#60c626cf486d5c53c44d84db1ec81cb90174cad3'
dependencies = ['core']
8 changes: 8 additions & 0 deletions examples/enums/Forc.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
[project]
authors = ["Fuel Labs <[email protected]>"]
entry = "main.sw"
implicit-std = false
license = "Apache-2.0"
name = "enums"

[dependencies]
16 changes: 16 additions & 0 deletions examples/enums/src/basic_enum.sw
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
library basic_enum;

// Declare the enum
enum Color {
Blue: (),
Green: (),
Red: (),
Silver: (),
Grey: (),
}

fn main() {
// To instantiate a variable with the value of an enum the syntax is
let blue = Color::Blue;
let silver = Color::Silver;
}
17 changes: 17 additions & 0 deletions examples/enums/src/enum_of_enums.sw
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
library enum_of_enums;

pub enum Error {
StateError: StateError,
UserError: UserError,
}

pub enum StateError {
Void: (),
Pending: (),
Completed: (),
}

pub enum UserError {
InsufficientPermissions: (),
Unauthorized: (),
}
17 changes: 17 additions & 0 deletions examples/enums/src/enum_of_structs.sw
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
library enum_of_structs;

struct Item {
price: u64,
amount: u64,
id: u64,
}

enum MyEnum {
Item: Item,
}

fn main() {
let my_enum = MyEnum::Item(Item {
price: 5, amount: 2, id: 42
});
}
9 changes: 9 additions & 0 deletions examples/enums/src/enums_avoid.sw
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
library enums_avoid;

dep enum_of_enums;
use enum_of_enums::{Error, StateError, UserError};

fn avoid() {
let error1 = Error::StateError(StateError::Void);
let error2 = Error::UserError(UserError::Unauthorized);
}
9 changes: 9 additions & 0 deletions examples/enums/src/enums_preferred.sw
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
library enums_preferred;

dep enum_of_enums;
use enum_of_enums::{StateError, UserError};

fn preferred() {
let error1 = StateError::Void;
let error2 = UserError::Unauthorized;
}
6 changes: 6 additions & 0 deletions examples/enums/src/main.sw
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
library enums;

dep basic_enum;
dep enums_avoid;
dep enums_preferred;
dep enum_of_structs;
2 changes: 2 additions & 0 deletions examples/structs/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
out
target
12 changes: 12 additions & 0 deletions examples/structs/Forc.lock
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
[[package]]
name = 'core'
dependencies = []

[[package]]
name = 'std'
source = 'git+https://github.com/fuellabs/sway?tag=v0.14.5#60c626cf486d5c53c44d84db1ec81cb90174cad3'
dependencies = ['core']

[[package]]
name = 'structs'
dependencies = []
8 changes: 8 additions & 0 deletions examples/structs/Forc.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
[project]
authors = ["Fuel Labs <[email protected]>"]
entry = "main.sw"
implicit-std = false
license = "Apache-2.0"
name = "structs"

[dependencies]
7 changes: 7 additions & 0 deletions examples/structs/src/data_structures.sw
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
library data_structures;

// Declare a struct type
pub struct Foo {
bar: u64,
baz: bool,
}
Loading

0 comments on commit 8e07f9a

Please sign in to comment.