gpt4 book ai didi

rust - 在 Rust 中居中动态字符串?

转载 作者:行者123 更新时间:2023-12-04 22:55:20 24 4
gpt4 key购买 nike

fn main() {
println!("{:=^50}", "Stuff");
println!("{:=^50}", format_args!("Stuff {}", 42));
}

有人会认为它没有理由不工作,但实际上,它没有:
======================Stuff=======================
Stuff 42

Playground .

我当然可以自己做,但是有没有内置的方法来做到这一点?

最佳答案

试试 this (见 fmt):

fn main() {
println!("{:=^50}", "Stuff");
println!("{:=^50}", format!("Stuff {}", 42));
}
输出:
======================Stuff=======================
=====================Stuff 42=====================

试试 this :
fn main() {
println!("{:=^50}", "Stuff");
println!("{:=^50}", std::fmt::format(format_args!("Stuff {}", 42)));
}
输出:
======================Stuff=======================
=====================Stuff 42=====================

format_args :

This macro produces a value of type fmt::Arguments. This value can be passed to the macros within std::fmt for performing useful redirection. All other formatting macros (format!, write!, println!, etc) are proxied through this one. format_args!, unlike its derived macros, avoids heap allocations.


Arguments :

The format_args! macro will safely create an instance of this structure. The macro validates the format string at compile-time so usage of the write and format functions can be safely performed.


Display for Arguments :
impl Display for Arguments<'_> {
fn fmt(&self, fmt: &mut Formatter<'_>) -> Result {
write(fmt.buf, *self)
}
}

关于rust - 在 Rust 中居中动态字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59070218/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com