本文簡要介紹rust語言中 Macro core::write 的用法。
用法
macro_rules! write {
($dst : expr, $($arg : tt) *) => { ... };
}將格式化數據寫入緩衝區。
此宏接受'writer'、格式字符串和參數列表。參數將根據指定的格式字符串進行格式化,並將結果傳遞給編寫器。 writer 可以是任何帶有write_fmt 方法的值;通常這來自 fmt::Write 或 io::Write 特征的實現。宏返回 write_fmt 方法返回的任何內容;通常是 fmt::Result 或 io::Result 。
有關格式字符串語法的更多信息,請參閱 std::fmt 。
例子
use std::io::Write;
fn main() -> std::io::Result<()> {
let mut w = Vec::new();
write!(&mut w, "test")?;
write!(&mut w, "formatted {}", "arguments")?;
assert_eq!(w, b"testformatted arguments");
Ok(())
}模塊可以同時導入 std::fmt::Write 和 std::io::Write 並在實現其中任何一個的對象上調用 write!,因為對象通常不會同時實現這兩者。但是,模塊必須導入限定的特征,以便它們的名稱不會衝突:
use std::fmt::Write as FmtWrite;
use std::io::Write as IoWrite;
fn main() -> Result<(), Box<dyn std::error::Error>> {
let mut s = String::new();
let mut v = Vec::new();
write!(&mut s, "{} {}", "abc", 123)?; // uses fmt::Write::write_fmt
write!(&mut v, "s = {:?}", s)?; // uses io::Write::write_fmt
assert_eq!(v, b"s = \"abc 123\"");
Ok(())
}注意:該宏也可以在no_std 設置中使用。在no_std 設置中,您負責組件的實現細節。
use core::fmt::Write;
struct Example;
impl Write for Example {
fn write_str(&mut self, _s: &str) -> core::fmt::Result {
unimplemented!();
}
}
let mut m = Example{};
write!(&mut m, "Hello World").expect("Not written");相關用法
- Rust write_volatile用法及代碼示例
- Rust write用法及代碼示例
- Rust write_unaligned用法及代碼示例
- Rust writeln用法及代碼示例
- Rust write_bytes用法及代碼示例
- Rust UdpSocket.set_multicast_loop_v6用法及代碼示例
- Rust i64.overflowing_add_unsigned用法及代碼示例
- Rust Box.downcast用法及代碼示例
- Rust BTreeMap.last_key_value用法及代碼示例
- Rust str.make_ascii_uppercase用法及代碼示例
- Rust u128.checked_pow用法及代碼示例
- Rust usize.wrapping_mul用法及代碼示例
- Rust AtomicU8.fetch_sub用法及代碼示例
- Rust PanicInfo.payload用法及代碼示例
- Rust MaybeUninit.assume_init_mut用法及代碼示例
- Rust String.try_reserve用法及代碼示例
- Rust Mutex.new用法及代碼示例
- Rust f32.exp用法及代碼示例
- Rust Result.unwrap_or_else用法及代碼示例
- Rust slice.sort_unstable_by_key用法及代碼示例
- Rust Formatter.precision用法及代碼示例
- Rust i128.log2用法及代碼示例
- Rust OsStr.to_ascii_uppercase用法及代碼示例
- Rust f32.hypot用法及代碼示例
- Rust RefCell.try_borrow_unguarded用法及代碼示例
注:本文由純淨天空篩選整理自rust-lang.org大神的英文原創作品 Macro core::write。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。
