while printing hex / octa / byte ,it print is decimal form .
is it possible to print hex / octa / byte numbers as it is which is declare to a variable using let without using string or character datatype ?
Also check the Rust's formatting language document for other features.
is there any other solutions other than format!()
What's wrong with format!()
?
I personally don't know any case where format
and friends won't work. If this is the case for you - well, I'm afraid that you'll have to write the formatting code yourself, since your case seem to be unique.
I am gonna guess that you wish to construct something that when "{}"
-displayed, is displayed with the format that you want / you don't want to impose on users to use the special formatting modifiers.
In that case, you can wrap your value in a type whose natural Display
delegates to the formatting formats that @Hyeonu has shown:
-
the most basic way to achieve this, although it may struggle with short-lived temporaries, is using
format_args!()
:format_args!("{:#x}", number)
is a value that borrowsnumber
and that is lazily displayed in hexadecimal.
To circumvent the issue with the short-lived temporary, you can go one step further and define your own lazy-formatting struct:
#[doc(hidden)]
pub use ::core::fmt;
pub
struct LazyFmt<F>(pub F);
impl<F> fmt::Display for LazyFmt<F>
where
F : Fn(&mut fmt::Formatter<'_>)
-> fmt::Result
,
{
fn fmt (self: &'_ Self, fmt: &'_ mut fmt::Formatter<'_>)
-> fmt::Result
{
(self.0)(fmt)
}
}
#[macro_export]
macro_rules! lazy_fmt {(
$fmt:expr $(, $args:expr)* $(,)?
) => (
$crate::LazyFmt(|fmt: &'_ mut $crate::fmt::Formatter<'_>| write!(fmt, $fmt $(, $args)*))
)}
so that you can use it as:
fn main ()
{
let b = lazy_fmt!("{:#x}", 0x12ffa); //Hexa
let c = lazy_fmt!("{:#o}", 0o7765); //octa
let d = lazy_fmt!("{:#b}", 0b111_000); //binary
//_ is virsual seperation in rust lang
println!("{}\n{}\n{}\n",b,c,d,);
}
This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.