summaryrefslogtreecommitdiffstats
path: root/src/doc/rust-by-example/src/scope/lifetime/struct.md
diff options
context:
space:
mode:
Diffstat (limited to '')
-rw-r--r--src/doc/rust-by-example/src/scope/lifetime/struct.md46
1 files changed, 46 insertions, 0 deletions
diff --git a/src/doc/rust-by-example/src/scope/lifetime/struct.md b/src/doc/rust-by-example/src/scope/lifetime/struct.md
new file mode 100644
index 000000000..aca0bfe62
--- /dev/null
+++ b/src/doc/rust-by-example/src/scope/lifetime/struct.md
@@ -0,0 +1,46 @@
+# Structs
+
+Annotation of lifetimes in structures are also similar to functions:
+
+```rust,editable
+// A type `Borrowed` which houses a reference to an
+// `i32`. The reference to `i32` must outlive `Borrowed`.
+#[derive(Debug)]
+struct Borrowed<'a>(&'a i32);
+
+// Similarly, both references here must outlive this structure.
+#[derive(Debug)]
+struct NamedBorrowed<'a> {
+ x: &'a i32,
+ y: &'a i32,
+}
+
+// An enum which is either an `i32` or a reference to one.
+#[derive(Debug)]
+enum Either<'a> {
+ Num(i32),
+ Ref(&'a i32),
+}
+
+fn main() {
+ let x = 18;
+ let y = 15;
+
+ let single = Borrowed(&x);
+ let double = NamedBorrowed { x: &x, y: &y };
+ let reference = Either::Ref(&x);
+ let number = Either::Num(y);
+
+ println!("x is borrowed in {:?}", single);
+ println!("x and y are borrowed in {:?}", double);
+ println!("x is borrowed in {:?}", reference);
+ println!("y is *not* borrowed in {:?}", number);
+}
+```
+
+### See also:
+
+[`struct`s][structs]
+
+
+[structs]: ../../custom_types/structs.md