Skip to content

Commit 11fba52

Browse files
committed
add out-pointer example
1 parent 30a4332 commit 11fba52

File tree

1 file changed

+25
-1
lines changed

1 file changed

+25
-1
lines changed

Diff for: src/libcore/mem.rs

+25-1
Original file line numberDiff line numberDiff line change
@@ -1022,6 +1022,30 @@ impl<T: ?Sized> DerefMut for ManuallyDrop<T> {
10221022
///
10231023
/// The compiler then knows to not make any incorrect assumptions or optimizations on this code.
10241024
///
1025+
/// ## out-pointers
1026+
///
1027+
/// You can use `MaybeUninit<T>` to implement "out-pointers": instead of returning data
1028+
/// from a function, pass it a pointer to some (uninitialized) memory to put the
1029+
/// result into. This can be useful when it is important for the caller to control
1030+
/// how the memory the result is stored in gets allocated, and you want to avoid
1031+
/// unnecessary moves.
1032+
///
1033+
/// ```
1034+
/// use std::mem::MaybeUninit;
1035+
///
1036+
/// unsafe fn make_vec(out: *mut Vec<i32>) {
1037+
/// // `write` does not drop the old contents, which is important.
1038+
/// out.write(vec![1, 2, 3]);
1039+
/// }
1040+
///
1041+
/// let mut v: MaybeUninit<Vec<i32>> = MaybeUninit::uninit();
1042+
/// unsafe { make_vec(v.as_mut_ptr()); }
1043+
/// // Now we know `v` is initialized! This also makes sure the vector gets
1044+
/// // properly dropped.
1045+
/// let v = unsafe { v.assume_init() };
1046+
/// assert_eq!(&v, &[1, 2, 3]);
1047+
/// ```
1048+
///
10251049
/// ## Initializing an array element-by-element
10261050
///
10271051
/// `MaybeUninit<T>` can be used to initialize a large array element-by-element:
@@ -1049,7 +1073,7 @@ impl<T: ?Sized> DerefMut for ManuallyDrop<T> {
10491073
/// unsafe { mem::transmute::<_, [Vec<u32>; 1000]>(data) }
10501074
/// };
10511075
///
1052-
/// println!("{:?}", &data[0]);
1076+
/// assert_eq!(&data[0], &[42]);
10531077
/// ```
10541078
///
10551079
/// You can also work with partially initialized arrays, which could

0 commit comments

Comments
 (0)