Skip to content

Commit

Permalink
Merge pull request #92 from rust-lang-nursery/guide-enums
Browse files Browse the repository at this point in the history
enums, variants, tuple structs
  • Loading branch information
nrc authored Oct 5, 2017
2 parents 6c702c4 + 5780c31 commit cb3cdaa
Showing 1 changed file with 50 additions and 3 deletions.
53 changes: 50 additions & 3 deletions guide/items.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
## Items

### Function definitions

In Rust, one finds functions by searching for `fn [function-name]`; It's
Expand Down Expand Up @@ -30,10 +32,10 @@ let y = (11, 22, 33);

### Enums

In the declaration, put each variant on its own line.
In the declaration, put each variant on its own line, block indented.

Format each variant accordingly as either a `struct`, `tuple struct`, or ident,
which doesn't require special formatting.
Format each variant accordingly as either a struct, tuple struct, or identifier,
which doesn't require special formatting (but without the `struct` keyword.

```rust
enum FooBar {
Expand All @@ -46,6 +48,22 @@ enum FooBar {
}
```

If a struct variant is *short* (TODO link to definition), it may be formatted on
one line. In this case, do not use a trailing comma for the field list, but do
put spaces around braces:

```rust
enum FooBar {
Error { err: Box<Error>, line: u32 },
}
```

In an enum with multiple struct variants, if any struct variant is written on
multiple lines, then the multi-line formatting should be used for all struct
variants. However, such a situation might be an indication that you should
factor out the fields of the variant into their own struct.


### Structs and Unions

Struct names follow on the same line as the `struct` keyword, with the opening
Expand All @@ -71,6 +89,10 @@ struct Foo {
}
```

Prefer using a unit struct to an empty struct (these only exist to simplify code
generation), but if you must use an empty struct, keep it on one line with no
space between the braces: `struct Foo;` or `struct Foo {}`.

The same guidelines are used for untagged union declarations.

```rust
Expand All @@ -82,6 +104,31 @@ union Foo {
}
```

### Tuple structs

Put the whole struct on one line if possible. Types in the parentheses should be
separated by a comma and space with no trailing comma. No spaces around the
parentheses or semi-colon:

```rust
pub struct Foo(String, u8);
```

Prefer unit structs to empty tuple structs (these only exist to simplify code
generation), e.g., `struct Foo;` rather than `struct Foo();`.

For more than a few fields, prefer a proper struct with named fields. Given
this, a tuple struct should always fit on one line. If it does not, block format
the fields with a field on each line and a trailing comma:

```rust
pub struct Foo(
String,
u8,
);
```


### Extern crate

`extern crate foo;`
Expand Down

0 comments on commit cb3cdaa

Please sign in to comment.