Skip to content

Commit 9a5c4d7

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 4c558f5 + 3d09017 commit 9a5c4d7

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
@@ -965,11 +965,61 @@ mod move_keyword {}
965965

966966
#[doc(keyword = "mut")]
967967
//
968-
/// A mutable binding, reference, or pointer.
968+
/// A mutable variable, reference, or pointer.
969969
///
970-
/// The documentation for this keyword is [not yet complete]. Pull requests welcome!
970+
/// `mut` can be used in several situations. The first is mutable variables,
971+
/// which can be used anywhere you can bind a value to a variable name. Some
972+
/// examples:
971973
///
972-
/// [not yet complete]: https://github.com/rust-lang/rust/issues/34601
974+
/// ```rust
975+
/// // A mutable variable in the parameter list of a function.
976+
/// fn foo(mut x: u8, y: u8) -> u8 {
977+
/// x += y;
978+
/// x
979+
/// }
980+
///
981+
/// // Modifying a mutable variable.
982+
/// # #[allow(unused_assignments)]
983+
/// let mut a = 5;
984+
/// a = 6;
985+
///
986+
/// assert_eq!(foo(3, 4), 7);
987+
/// assert_eq!(a, 6);
988+
/// ```
989+
///
990+
/// The second is mutable references. They can be created from `mut` variables
991+
/// and must be unique: no other variables can have a mutable reference, nor a
992+
/// shared reference.
993+
///
994+
/// ```rust
995+
/// // Taking a mutable reference.
996+
/// fn push_two(v: &mut Vec<u8>) {
997+
/// v.push(2);
998+
/// }
999+
///
1000+
/// // A mutable reference cannot be taken to a non-mutable variable.
1001+
/// let mut v = vec![0, 1];
1002+
/// // Passing a mutable reference.
1003+
/// push_two(&mut v);
1004+
///
1005+
/// assert_eq!(v, vec![0, 1, 2]);
1006+
/// ```
1007+
///
1008+
/// ```rust,compile_fail,E0502
1009+
/// let mut v = vec![0, 1];
1010+
/// let mut_ref_v = &mut v;
1011+
/// ##[allow(unused)]
1012+
/// let ref_v = &v;
1013+
/// mut_ref_v.push(2);
1014+
/// ```
1015+
///
1016+
/// Mutable raw pointers work much like mutable references, with the added
1017+
/// possibility of not pointing to a valid object. The syntax is `*mut Type`.
1018+
///
1019+
/// More information on mutable references and pointers can be found in```
1020+
/// [Reference].
1021+
///
1022+
/// [Reference]: ../reference/types/pointer.html#mutable-references-mut
9731023
mod mut_keyword {}
9741024

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

0 commit comments

Comments
 (0)