Rust 使用println以可变次数打印字符
我想使用Rust 使用println以可变次数打印字符,rust,Rust,我想使用println和功能强大的格式化工具以特定次数打印字符。当然,这在循环中是可能的,如下所示: fn give_love(count: usize) { print!("Here is love for you: "); for i in 0..count { print!("♥"); } println!(""); } 但是我既不想写循环,也不想打印三个s。如何缩短/更好地执行此操作?代码的解决方案 下面是一些不传递空字符串的示例: pr
println
和功能强大的格式化工具
以特定次数打印字符。当然,这在循环中是可能的,如下所示:
fn give_love(count: usize) {
print!("Here is love for you: ");
for i in 0..count {
print!("♥");
}
println!("");
}
但是我既不想写循环,也不想打印三个s。如何缩短/更好地执行此操作?代码的解决方案
下面是一些不传递空字符串的示例:
println!("love: {:♥<5}", "#"); // love: #♥♥♥♥
println!("love: {:♥>5}", "#"); // love: ♥♥♥♥#
println!("love: {:♥^5}", "#"); // love: ♥♥#♥♥
println!(“爱:{:♥5}", "#"); // 爱:♥♥♥♥#
普林顿!(“爱:{:♥^5}", "#"); // 爱:♥♥#♥♥
如果希望以更简洁的方式重复任何显示
可显示项而不创建中间分配,则可以创建包装结构并编写执行重复的自定义显示
实现:
use std::fmt::{self, Display};
#[derive(Clone, Copy)]
struct DisplayRepeat<T>(usize, T);
impl<T: Display> Display for DisplayRepeat<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
for _ in 0..self.0 {
self.1.fmt(f)?;
}
Ok(())
}
}
fn repeat<T>(times: usize, item: T) -> DisplayRepeat<T> {
DisplayRepeat(times, item)
}
fn main() {
println!("Here is love for you: {}", repeat(10, '♥'));
}
使用std::fmt::{self,Display};
#[派生(克隆、复制)]
结构显示重复(usize,T);
DisplayRepeat的impl显示{
fn fmt(&self,f:&mut fmt::Formatter)->fmt::Result{
对于0中的u0..self.0{
自我。1。fmt(f)?;
}
好(())
}
}
fn重复(次数:usize,项目:T)->显示重复{
显示重复(次数、项目)
}
fn main(){
println!(“这是对你的爱:{}”,重复(10,'♥'));
}
或者(提到一个不那么聪明的选择),您可以重复('♥').收集::()
println!("love: {:♥<3}", ""); // love: ♥♥♥
println!("love: {:♥<1$}", "", 5); // love: ♥♥♥♥♥
println!("love: {:♥<5}", "#"); // love: #♥♥♥♥
println!("love: {:♥>5}", "#"); // love: ♥♥♥♥#
println!("love: {:♥^5}", "#"); // love: ♥♥#♥♥
use std::fmt::{self, Display};
#[derive(Clone, Copy)]
struct DisplayRepeat<T>(usize, T);
impl<T: Display> Display for DisplayRepeat<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
for _ in 0..self.0 {
self.1.fmt(f)?;
}
Ok(())
}
}
fn repeat<T>(times: usize, item: T) -> DisplayRepeat<T> {
DisplayRepeat(times, item)
}
fn main() {
println!("Here is love for you: {}", repeat(10, '♥'));
}