2 个不稳定版本

0.2.0 2024年7月13日
0.1.0 2024年6月8日

#1563 in 算法

Download history 55/week @ 2024-06-03 24/week @ 2024-06-10 1/week @ 2024-07-01 120/week @ 2024-07-08 17/week @ 2024-07-15 8/week @ 2024-07-22

146 个月下载量

MIT 许可证

185KB
3K SLoC

模块 :: format_tools

experimental rust-status docs.rs Open in Gitpod discord

将格式化和序列化机制集合到字符串中。

基本用法

使用 to_string_with_fallback 宏将值转换为具有主格式化和回退格式的字符串。

fn main()
{
  // Import necessary traits and the macro from the `format_tools` crate.
  use core::fmt;
  use format_tools::
  {
    WithDebug,
    WithDisplay,
    to_string_with_fallback,
  };

  // Define a struct that implements both Debug and Display traits.
  struct Both;

  // Implement the Debug trait for the Both struct.
  impl fmt::Debug for Both
  {
    fn fmt( &self, f : &mut fmt::Formatter< '_ > ) -> fmt::Result
    {
      write!( f, "This is debug" )
    }
  }

  // Implement the Display trait for the Both struct.
  impl fmt::Display for Both
  {
    fn fmt( &self, f : &mut fmt::Formatter< '_ > ) -> fmt::Result
    {
      write!( f, "This is display" )
    }
  }

  // Define a struct that implements only the Debug trait.
  struct OnlyDebug;

  // Implement the Debug trait for the OnlyDebug struct.
  impl fmt::Debug for OnlyDebug
  {
    fn fmt( &self, f : &mut fmt::Formatter< '_ > ) -> fmt::Result
    {
      write!( f, "This is debug" )
    }
  }

  // Example usage: Using Both which implements both Debug and Display.
  let src = Both;
  // Convert the struct to a string using `to_string_with_fallback` macro.
  // The primary formatting method WithDisplay is used.
  let got = to_string_with_fallback!( WithDisplay, WithDebug, &src );
  let exp = "This is display".to_string();
  // Assert that the result matches the expected value.
  assert_eq!( got, exp );

  // Example usage: Using OnlyDebug which implements only Debug.
  let src = OnlyDebug;
  // Convert the struct to a string using `to_string_with_fallback` macro.
  // The primary formatting method WithDisplay is not available, so the fallback WithDebug is used.
  let got = to_string_with_fallback!( WithDisplay, WithDebug, &src );
  let exp = "This is debug".to_string();
  // Assert that the result matches the expected value.
  assert_eq!( got, exp );

}

添加到您的项目

cargo add format_tools

从仓库尝试

git clone https://github.com/Wandalen/wTools
cd wTools
cd examples/foramt_tools_trivial
cargo run

依赖关系

~2MB
~42K SLoC