运算符和格式化输出
运算符
rust
let x = 5;
rust
let x = 5;
let y = 10;
let z = x + y;
rust
let mut x = 5;
x += 1;
rust
let x = 5;
let y = 10;
x == y;
x != y;
x > y;
x < y;
x >= y;
x <= y;
rust
let x = true;
let y = false;
x && y;
x || y;
!x;
rust
let x = 0b1111_0000;
let y = 0b1010;
x & y;
x | y;
x ^ y;
!x;
x << 2;
x >> 2;
rust
let x = 5;
let y = x as f64;
println!("{}", y);
格式化输出
rust
format!("Hello, {}!", "world");
// 输出到标准输出
print!("Hello, world!");
println!("Hello, world!");
// 错误输出
eprintln!("Hello, world!");
// 输出到标准&mut io::Write
writeln!("Hello, world!");
// 通配符和位置
format!("{0}, this is {1}. {1}, this is {0}", "Alice", "Bob");
// "Alice, this is Bob. Bob, this is Alice"
// 通配符和命名参数
format!("{subject} {verb} {object}", object="the lazy dog", subject="the quick brown fox", verb="jumps over");
// "the quick brown fox jumps over the lazy dog"
// 输出不同的进制数
println!("{}", 10);
println!("{:x}", 10); // 16进制
println!("{:X}", 10); // 16进制大写
println!("{:o}", 10); // 8进制
println!("{:b}", 10); // 2进制
println!("{:e}", 10.0); // 科学计数法
println!("{:E}", 10.0); // 科学计数法大写
println!("{:?}", (3, 4)); // 显示调试信息
println!("{:#?}", (3, 4)); // 显示调试信息,带缩进
println!("{:p}", &10); // 显示指针地址
println!("{:>5}", 1); // 右对齐
println!("{:05}", 42); // 整数格式化时填充宽度
println!("{:05.2}", 42.4256); // 小数格式化时填充宽度和精度(四舍五入)
println!("{:05b}", 12); // 二进制格式化时填充宽度