Various utility functions useful in the generic context.
Functions
-
Take any parameter and discard the result
Example
use std::util::discard; // Use foreach to loop through the iterator, but don't do anything with the values. (0..10) .inspect(|i: i32| { println!("{}", i); }) .foreach(discard::<i32>);
Run this example -
Cast a value to a different type.
Example
use std::util::cast; #[cfg(target_pointer_width = "64")] let x: u64; #[cfg(target_pointer_width = "32")] let x: u32; // We do not know whether x is `u64` or `u32`, but we know 10 // fits in either. x = cast(10);
Run this example -
Coerce a value to a different type without casting
Example
use std::util::coerce; use std::mem::slice; let x: Option<&mut [u8]> = Option::some(slice::alloc(10)); defer x.unwrap().free(); let _: Option<&[u8]> = x.map(coerce::<&mut [u8], &[u8]>);
Run this example -
Reinterpret the bits of the value as another type. Requires that the types have the same size and alignment.
Examples
use std::util::transmute; let x: u64 = 0x400921fb54442d18; let y: f64 = transmute(x); assert_eq!(y, 3.14159265358979323846264338327950288f64);
Run this exampleuse std::util::transmute; let x: u8 = 123; let y: u32 = transmute(x); // compile error
Run this example -
Dereference a pointer.
-
Produce the only value of a unit type out of thin air.
Does not work for the never type.
Example
use std::builtins::NamedFunction; use std::util::unit; fn hello_world() { println!("Hello, world!"); } fn call<F: Fn() + NamedFunction>() { // Named functions are a family of zero-sized types let f = unit::<F>(); f(); } call::<hello_world>();
Run this example -
Applies a function on the provided value.
Useful in method chaining
Example
use std::util::apply; let v = 3 .apply(|v: i32| -> i32 { v + 1 }) .apply(|v: i32| -> Option<i32> { Option::some(v) }) .apply(|v: Option<i32>| -> i32 { v.unwrap() }); assert_eq!(v, Option::some(3 + 1).unwrap());
Run this example