是否可以使用变量作为格式的fill参数!宏?

编程入门 行业动态 更新时间:2024-10-27 17:18:47
本文介绍了是否可以使用变量作为格式的fill参数!宏?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我想使用format!宏模仿Python的rjust,ljust和center函数,但是我只能找到一种解决方案,您可以传入字符串和宽度.如果您要传递填充参数,则无法使用.

I wanted to imitate Python's rjust, ljust, and center functions using the format! macro, but I was only able to work out a solution where you can pass in the string and the width. If you want to pass in the fill-argument it doesn't work.

文档告诉我可以为format!提供变量,对于width参数,它可以正常工作.当我尝试使用变量进行填充时,编译器无法识别该模式.

The documentation tells me that it is possible to provide variables to format! and for the width argument it works just fine. When I try to use a variable for fill, the compiler does not recognize the pattern.

宽度作为变量起作用:

fn rjust(text: &str, width: usize, fill: Option<char>) -> String { format!("{text:>width$}", text = text, width = width) } println!("{}", rjust("Hello", 10)); // " Hello"

将填充值提供为变量不起作用:

Providing the fill as a variable does not work:

fn rjust(text: &str, width: usize, fill: char) -> String { format!( "{text:fill>width$}", text = text, fill = fill, width = width ) } println!("{}", rjust("Hello", 20, '*'));

错误消息:

error: invalid format string: expected `'}'`, found `'>'` --> src/lib.rs:4:24 | 4 | "{text:fill>width$}", | - ^ expected `}` in format string | | | because of this opening brace | = note: if you intended to print `{`, you can escape it using `{{`

如果我提供的是单个字符而不是填充变量,那么它可以正常工作.注意*字符:

If I provide a single character instead of the fill-variable, it works fine. Notice the * character:

fn rjust(text: &str, width: usize, fill: char) -> String { format!("{text:*>width$}", text = text, width = width) } println!("{}", rjust("Hello", 20, '_')); // ***************Hello

我希望填充变量版本的功能与硬编码的*字符版本相同.

I expected the fill-variable version to work the same as the hardcoded * character version.

一种解决方法是从宽度中减去文本的长度,然后创建一个由填充字符组成的长度(填充长度)的String并将其连接起来:

A workaround is to subtract the length of the text from the width and then create a String of that length (fill-length) made of fill-characters and concatenate them:

fn rjust(text: &str, width: usize, fill: char) -> String { let fill_len = width - text.len(); let fill_str: String = (0..fill_len).map(|_| fill).collect(); String::from(fill_str + text) } println!("{}", rjust("Hello", 20, '*')); // ***************Hello

推荐答案

不幸的是,没有内置方法可以做到这一点.

Unfortunately there is no built-in way to do this.

格式化语法是由早期Rust使用者采用的功能演变而来的.简洁意味着新功能在事实之后很难添加.

The formatting syntax evolved with features that early Rust adopters needed at the time. Its terseness means that new features are very difficult to add after the fact.

更多推荐

是否可以使用变量作为格式的fill参数!宏?

本文发布于:2023-05-27 09:56:05,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/285732.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:可以使用   变量   参数   格式   fill

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!