Skip to content

Commit eeb0633

Browse files
committed
sync primitive_docs
1 parent 13e0f72 commit eeb0633

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

std/src/primitive_docs.rs

+26
Original file line numberDiff line numberDiff line change
@@ -1338,6 +1338,32 @@ mod prim_ref {}
13381338
/// is a reference to the function-specific ZST. `&bar` is basically never what you
13391339
/// want when `bar` is a function.
13401340
///
1341+
/// ### Casting to and from integers
1342+
///
1343+
/// You cast function pointers directly to integers:
1344+
///
1345+
/// ```rust
1346+
/// let fnptr: fn(i32) -> i32 = |x| x+2;
1347+
/// let fnptr_addr = fnptr as usize;
1348+
/// ```
1349+
///
1350+
/// However, a direct cast back is not possible. You need to use `transmute`:
1351+
///
1352+
/// ```rust
1353+
/// # let fnptr: fn(i32) -> i32 = |x| x+2;
1354+
/// # let fnptr_addr = fnptr as usize;
1355+
/// let fnptr = fnptr_addr as *const ();
1356+
/// let fnptr: fn(i32) -> i32 = unsafe { std::mem::transmute(fnptr) };
1357+
/// assert_eq!(fnptr(40), 42);
1358+
/// ```
1359+
///
1360+
/// Crucially, we `as`-cast to a raw pointer before `transmute`ing to a function pointer.
1361+
/// This avoids an integer-to-pointer `transmute`, which can be problematic.
1362+
/// Transmuting between raw pointers and function pointers (i.e., two pointer types) is fine.
1363+
///
1364+
/// Note that all of this is not portable to platforms where function pointers and data pointers
1365+
/// have different sizes.
1366+
///
13411367
/// ### Traits
13421368
///
13431369
/// Function pointers implement the following traits:

0 commit comments

Comments
 (0)