You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Safely cast &T to &U where the struct U contains a single field of
type T.
[dependencies]
ref-cast = "1.0"
Basic example
use ref_cast::RefCast;#[derive(RefCast)]#[repr(transparent)]structU(String);fnmain(){let s = String::new();// Safely cast from `&String` to `&U`.let u = U::ref_cast(&s);}
Note that #[repr(transparent)] is required in order for the conversion to be
sound. The derive macro will refuse to compile if that is not present.
Realistic example
Suppose we have a multidimensional array represented in a flat buffer in
row-major order for performance reasons, but we want to expose an indexing
operation that works in column-major order because it is more intuitive in
the context of our application.
constMAP_WIDTH:usize = 4;structTile(u8);structTileMap{storage:Vec<Tile>,}// `tilemap[x][y]` should give us `tilemap.storage[y * MAP_WIDTH + x]`.
The signature of the Index trait in Rust is such that the output is
forced to be borrowed from the type being indexed. So something like the
following is not going to work.
structColumn<'a>{tilemap:&'aTileMap,x:usize,}// Does not work! The output of Index must be a reference that is// borrowed from self. Here the type Column is not a reference.implIndex<usize>forTileMap{fnindex(&self,x:usize) -> Column{assert!(x < MAP_WIDTH);Column{tilemap:self, x }}}impl<'a>Index<usize>forColumn<'a>{fnindex(&self,y:usize) -> &Tile{&self.tilemap.storage[y *MAP_WIDTH + self.x]}}
Licensed under either of Apache License, Version
2.0 or MIT license at your option.
Unless you explicitly state otherwise, any contribution intentionally submitted
for inclusion in this crate by you, as defined in the Apache-2.0 license, shall
be dual licensed as above, without any additional terms or conditions.
About
Safely cast &T to &U where the struct U contains a single field of type T.