Printing hex / octa / byte in rust

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 ?

Sure you can.

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 borrows number 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:

pub use ::core::fmt;

struct LazyFmt<F>(pub F);

impl<F> fmt::Display for LazyFmt<F>
    F : Fn(&mut fmt::Formatter<'_>)
          -> fmt::Result
    fn fmt (self: &'_ Self, fmt: &'_ mut fmt::Formatter<'_>)
      -> fmt::Result

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

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.