如何将格式良好的表格打印到控制台?

时间:2015-05-21 16:24:29

标签: rust println

我有一个程序打印出应该打印成看起来像表的格式的数据。但是,当数字长于2时,表格会中断。我知道width中的std::fmt参数,但我无法理解它。

当前输出:

---------------------------------------
| total | blanks: | comments: | code: |
---------------------------------------
|  0   |    0    |    0     |    0  |
|  77   |    0    |    3     |    74  |
|  112   |    0    |    6     |    106  |
|  178   |    0    |    6     |    172  |
|  218   |    0    |    7     |    211  |
|  289   |    0    |    8     |    281  |
|  380   |    0    |    9     |    371  |
|  460   |    0    |    10     |    450  |
|  535   |    0    |    11     |    524  |
|  611   |    0    |    12     |    599  |
|  692   |    0    |    14     |    678  |
|  772   |    0    |    17     |    755  |
|  873   |    0    |    18     |    855  |
|  963   |    0    |    19     |    944  |
|  1390   |    0    |    19     |    1371  |
|  1808   |    0    |    19     |    1789  |
|  2011   |    0    |    19     |    1992  |
|  2259   |    0    |    19     |    2240  |
|  2294   |    0    |    19     |    2275  |
|  2349   |    0    |    19     |    2330  |
|  2376   |    0    |    19     |    2357  |
|  2430   |    0    |    19     |    2411  |
|  2451   |    0    |    19     |    2432  |
|  2515   |    13    |    19     |    2483  |
|  2559   |    13    |    19     |    2527  |

2 个答案:

答案 0 :(得分:17)

语法类似于Python中的str.format语法。这样:

fn main() {
    println!(
        "{0: <10} | {1: <10} | {2: <10} | {3: <10}",
        "total", "blanks", "comments", "code"
    );
    println!("{0: <10} | {1: <10} | {2: <10} | {3: <10}", 0, 0, 0, 0);
    println!("{0: <10} | {1: <10} | {2: <10} | {3: <10}", 77, 0, 3, 74);
    println!("{0: <10} | {1: <10} | {2: <10} | {3: <10}", 112, 0, 6, 106);
    println!(
        "{0: <10} | {1: <10} | {2: <10} | {3: <10}",
        460, 0, 10, 1371
    );
}

playground

产生以下输出:

total      | blanks     | comments   | code      
0          | 0          | 0          | 0         
77         | 0          | 3          | 74        
112        | 0          | 6          | 106       
460        | 0          | 10         | 1371  

答案 1 :(得分:1)

或者您可以使用专门的板条箱来格式化表格prettytable-rs