我正在学习/试验Rust,在我用这种语言找到的所有优雅中,有一个让我感到困惑并且看起来完全不合适的特点.
在进行方法调用时,Rust会自动取消引用指针.我做了一些测试来确定确切的行为:
struct X { val: i32 }
impl std::ops::Deref for X {
type Target = i32;
fn deref(&self) -> &i32 { &self.val }
}
trait M { fn m(self); }
impl M for i32 { fn m(self) { println!("i32::m()"); } }
impl M for X { fn m(self) { println!("X::m()"); } }
impl M for &X { fn m(self) { println!("&X::m()"); } }
impl M for &&X { fn m(self) { println!("&&X::m()"); } }
impl M for &&&X { …Run Code Online (Sandbox Code Playgroud) 我需要一个完全内存中的对象,我可以给予BufReader和BufWriter.像Python这样的东西StringIO.我想使用通常与Files 一起使用的方法来写入和读取这样的对象.
有没有办法使用标准库?
我正在从文件中读取原始数据,我想将其转换为整数:
fn main() {
let buf: &[u8] = &[0, 0, 0, 1];
let num = slice_to_i8(buf);
println!("1 == {}", num);
}
pub fn slice_to_i8(buf: &[u8]) -> i32 {
unimplemented!("what should I do here?")
}
Run Code Online (Sandbox Code Playgroud)
我会在C中进行类型转换,但是我在Rust中做什么?
Vec支持std::io::Write,所以代码可以写成带有File或Vec,例如.从API参考,看起来既不Vec支持也不支持切片std::io::Read.
有没有方便的方法来实现这一目标?它是否需要编写包装器结构?
下面是一个工作代码的示例,它读取和写入一个文件,其中一行注释应该读取一个向量.
use ::std::io;
// Generic IO
fn write_4_bytes<W>(mut file: W) -> Result<usize, io::Error>
where W: io::Write,
{
let len = file.write(b"1234")?;
Ok(len)
}
fn read_4_bytes<R>(mut file: R) -> Result<[u8; 4], io::Error>
where R: io::Read,
{
let mut buf: [u8; 4] = [0; 4];
file.read(&mut buf)?;
Ok(buf)
}
// Type specific
fn write_read_vec() {
let mut vec_as_file: Vec<u8> = Vec::new();
{ // Write
println!("Writing Vec... {}", write_4_bytes(&mut vec_as_file).unwrap()); …Run Code Online (Sandbox Code Playgroud)