Skip to content

Commit 7f1eb2e

Browse files
authored
Rollup merge of rust-lang#73621 - poliorcetics:mut-keyword, r=steveklabnik
Document the mut keyword Partial fix for rust-lang#34601. Documentation for the `mut` keyword. I think it's okay for it to be quite short, this is not the book not the reference, but if you find something is missing, do not hesitate to tell me.
2 parents f1ca34e + 3d09017 commit 7f1eb2e

File tree

1 file changed

+53
-3
lines changed

1 file changed

+53
-3
lines changed

src/libstd/keyword_docs.rs

+53-3
Original file line numberDiff line numberDiff line change
@@ -983,11 +983,61 @@ mod move_keyword {}
983983

984984
#[doc(keyword = "mut")]
985985
//
986-
/// A mutable binding, reference, or pointer.
986+
/// A mutable variable, reference, or pointer.
987987
///
988-
/// The documentation for this keyword is [not yet complete]. Pull requests welcome!
988+
/// `mut` can be used in several situations. The first is mutable variables,
989+
/// which can be used anywhere you can bind a value to a variable name. Some
990+
/// examples:
989991
///
990-
/// [not yet complete]: https://github.com/rust-lang/rust/issues/34601
992+
/// ```rust
993+
/// // A mutable variable in the parameter list of a function.
994+
/// fn foo(mut x: u8, y: u8) -> u8 {
995+
/// x += y;
996+
/// x
997+
/// }
998+
///
999+
/// // Modifying a mutable variable.
1000+
/// # #[allow(unused_assignments)]
1001+
/// let mut a = 5;
1002+
/// a = 6;
1003+
///
1004+
/// assert_eq!(foo(3, 4), 7);
1005+
/// assert_eq!(a, 6);
1006+
/// ```
1007+
///
1008+
/// The second is mutable references. They can be created from `mut` variables
1009+
/// and must be unique: no other variables can have a mutable reference, nor a
1010+
/// shared reference.
1011+
///
1012+
/// ```rust
1013+
/// // Taking a mutable reference.
1014+
/// fn push_two(v: &mut Vec<u8>) {
1015+
/// v.push(2);
1016+
/// }
1017+
///
1018+
/// // A mutable reference cannot be taken to a non-mutable variable.
1019+
/// let mut v = vec![0, 1];
1020+
/// // Passing a mutable reference.
1021+
/// push_two(&mut v);
1022+
///
1023+
/// assert_eq!(v, vec![0, 1, 2]);
1024+
/// ```
1025+
///
1026+
/// ```rust,compile_fail,E0502
1027+
/// let mut v = vec![0, 1];
1028+
/// let mut_ref_v = &mut v;
1029+
/// ##[allow(unused)]
1030+
/// let ref_v = &v;
1031+
/// mut_ref_v.push(2);
1032+
/// ```
1033+
///
1034+
/// Mutable raw pointers work much like mutable references, with the added
1035+
/// possibility of not pointing to a valid object. The syntax is `*mut Type`.
1036+
///
1037+
/// More information on mutable references and pointers can be found in```
1038+
/// [Reference].
1039+
///
1040+
/// [Reference]: ../reference/types/pointer.html#mutable-references-mut
9911041
mod mut_keyword {}
9921042

9931043
#[doc(keyword = "pub")]

0 commit comments

Comments
 (0)