2016年12月27日 星期二

[Rust] 格式化輸出

Rust也可以像C的printf一樣格式化輸出


fn main()
{
    let x=10*5;
    println!("x={}",x);
}


輸出為:

x=50


試試字串

fn main()
{
    let name="boywhy";
    println!("My Name is {}",name);
}

輸出為:


My Name is boywhy


也可以透過指定Index的方式輸出



fn main()
{
  println!("{0}, this is {1}. {1}, this is {0}", "Alice", "Bob");
}

輸出為:


Alice, this is Bob. Bob, this is Alice


也可以透過命名參數來格式化輸出


fn main()
{
    println!("{subject} {verb} {object}",
             object="the lazy dog",
             subject="the quick brown fox",
             verb="jumps over");
}

輸出為:


the quick brown fox jumps over the lazy dog


也可以直接指定輸出為進制 ,例如{:b}


fn main()
{
  println!("{} of {:b} people know binary, the other half don't", 1, 2);  
}


1 of 10 people know binary, the other half don't

共輸出長度為6的number,所以輸出了5個空白以及1個數值


fn main()
{
 println!("{number:>width$}", number=1, width=6);i
}

輸出為      1


也可以輸出補0,差別在width$前面要補0


fn main()
{
 println!("{number:>0width$}", number=1, width=6);i
}

輸出為:


000001




參考資料:

1.2 Formatted print

沒有留言:

張貼留言