【Rust】格式化输出

格式化输出

格式化输出函数

Rust宏含义对应c/c++函数
print!将格式化文本输出到标准输出print, cout
println!将格式化文本输出到标准输出,带换行print格式加\n , cout加std::endl
eprint将格式化文本输出到标准错误print,cerr
eprintln!将格式化文本输出到标准错误,带换行print格式加\n , cerr加std::endl
format!将格式化文本输出到 String 字符串sprint,stringstream

例子

{} 为占位符,等同于c中%d,%f的%。

fn main() {
    println!(); // 只换行
    println!("hello"); 
    let w = "world";
    println!("hello {}", w);
    let h = "hello";
    let hw = format!("{} {}", h, w);
    println!("{}", hw);
}

输出

  
hello
hello world
hello world

占位符 {} 和 {:?}

占位符用途
{}实现了 std::fmt::Display 特征的类型才能使用,用于自定义显示输出
{:?}实现了 std::fmt::Debug 特征的类型才能使用,用于调试

大多数 Rust 类型都实现了 Debug 特征,结构体,枚举需要实现Debug 特征。
基础类型都实现了Display 特征,对于vector,tuple,结构体,枚举需要自己实现Display 特征。

例子

fn main() {
    let n:u16 = 100;
    println!("{}", n);
    println!("{:?}", n);
    let w = "world";
    println!("hello {}", w);
    println!("hello {:?}", w);
    let b:bool = false;
    println!("bool: {}", b);
    println!("bool: {:?}", b);
    let v = vec![1, 2, 3];
    //println!("vector: {}", v);   // 默认不支持
    println!("vector: {:?}", v); 
    let t = (100, "string", 1.0);
    //println!("vector: {}", t);   // 默认不支持
    println!("vector: {:?}", t);     
}

输出

100
100
hello world
hello "world"
bool: false
bool: false
vector: [1, 2, 3]
vector: (100, "string", 1.0)

支持Debug特征

#[derive(Debug)] 通过增加该属性宏,自动为结构体,枚举实现了Debug特征。

dbg! 也可以打印,用于调试:

  1. dbg!打印值连同宏调用的源位置以及表达式的源代码。
  2. dbg! 输出到stderr。
  3. 不要依赖此宏打印,打印值可能会在未来发生变化。
#[derive(Debug)]
struct Rectangle {
    width: u32,
    height: u32,
}

fn main() {
    let rect1 = Rectangle {
        width: 50,
        height: 80
    };
    
    dbg!(&rect1);
    println!("{:?}", rect1);
}

支持Display 特征

use std::fmt;

struct Rectangle {
    width: u32,
    height: u32,
}

impl fmt::Display for Rectangle {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "Display: ({}, {})", self.width, self.height)
    }
}

fn main() {
    let rect1 = Rectangle {
        width: 50,
        height: 80
    };
    println!("{}", rect1);
} 

更多格式化格式,参考标准库文档
std::fmt

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值