使用imple为结构体添加方法
给结构做添加方法,好象是我接触编程以来的新事物,作者通过说明其他语言的类,与Rust的给结构体添加方法,用了图形来表示。二者目的一样。
在以下代码中,使用impl来改善一个File的操作:
#![allow(unused_variables)]
#[derive(Debug)]
struct File {
name: String,
data: Vec<u8>,
}
impl File {
fn new(name: &str) -> File {
File {
name: String::from(name),
data: Vec::new(),
}
}
fn new_with_data(
name: &str,
data: &Vec<u8>,
) -> File {
let mut f = File::new(name);
f.data = data.clone();
f
}
fn read(
self: &File,
save_to: &mut Vec<u8>,
) -> usize {
let mut tmp = self.data.clone();
let read_length = tmp.len();
save_to.reserve(read_length);
save_to.append(&mut tmp);
read_length
}
}
fn open(f: &mut File) -> bool {
true
}
fn close(f: &mut File) -> bool {
true
}
fn main() {
let f3_data: Vec<u8> = vec![
114,117,115,116, 33
];
let mut f3 = File::new_with_data("2.txt", &f3_data);
let mut buffer: Vec<u8> = vec![];
open( &mut f3);
let f3_length = f3.read(&mut buffer);
close(&mut f3);
let text = String::from_utf8_lossy(&buffer);
println!("{:?}",f3);
println!("{} is {} bytes long!", &f3.name, f3_length);
println!("{}",text);
}
在这个例子中,给File添加了new,read方法,这使得操作起来更方便。
|