Read
trait | link
Write
trait | link
- 返回值为
std::io::Result
而不是 std::Result
type Result<T> = Result<T, std::io::Error>
use std::io;
use std::io::prelude::*;
use std::fs::File;
fn main() -> io::Result<()> {
let mut f = File::open("/tmp/foo.txt")?;
let mut buffer = [0; 10];
// read up to 10 bytes
f.read(&mut buffer)?;
println!("buffer1 = {buffer:?}");
let s1: String = String::from_utf8(buffer.to_vec()).unwrap();
println!("buffer2 = {s1:?}");
Ok(())
}
buffer1 = [97, 97, 97, 32, 98, 98, 98, 32, 99, 99]
buffer2 = "aaa bbb cc"
use std::io;
use std::io::prelude::*;
use std::fs::File;
fn main() -> io::Result<()> {
let mut buffer = File::create("/tmp/foo.out")?;
write!(buffer, "Hello {}!", "Jack").unwrap();
Ok(())
}
- BufReader
- BufWriter
- Json 工具 | serde
cargo add serde --features derive
cargo add serde_json
cargo add serde_derive
use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize, Debug)]
struct Point {
x: i32,
y: i32,
}
fn main() {
let point = Point { x: 1, y: 2 };
// Convert the Point to a JSON string.
let serialized = serde_json::to_string(&point).unwrap();
// Prints serialized = {"x":1,"y":2}
println!("serialized = {}", serialized);
// Convert the JSON string back to a Point.
let deserialized: Point = serde_json::from_str(&serialized).unwrap();
// Prints deserialized = Point { x: 1, y: 2 }
println!("deserialized = {:?}", deserialized);
}
error: Could not compile `cargow9PkJw`.