Rsut中的特征类似于CSharp中的接口
特征定义: trait 定义特征名
如下定义一个特征Playable于media.rs文件中:
pub trait Playable{ fn play(&self); fn pause(){ println!("Paused"); } }
main.rs文件中:
mod media; use media::Playable; struct Audio(String); struct Video(String); impl Playable for Audio{ fn play(&self){ println!("Now playing audio:{}",self.0) } } ///impl关键字后跟特征名来声明特征实现,for后跟要实现的特征类型 impl Playable for Video{ fn play(&self){ println!("Now playing video:{}",self.0) } } fn main() { let audio = Audio("蓝莲花.mp3".to_string()); let video = Video("天若有情.mkv".to_string()); audio.play(); video.play(); }
终端中运行:
cargo build
cargo run
结果如下:
注:以上代码参照《精通Rust》一书