面试题答案
一键面试- 实现自定义扩展方法的一般步骤:
- 定义trait:使用
trait
关键字定义一个新的trait,在这个trait中声明要添加的方法。 - 为类型实现trait:使用
impl
关键字为目标类型(String
或&str
)实现刚才定义的trait,在实现中编写方法的具体逻辑。
- 定义trait:使用
- 示例:为字符串添加计算单词数量的方法:
// 定义trait
trait StringExtensions {
fn count_words(&self) -> usize;
}
// 为&str实现trait
impl StringExtensions for &str {
fn count_words(&self) -> usize {
self.split_whitespace().count()
}
}
fn main() {
let s = "Hello world Rust";
let word_count = s.count_words();
println!("单词数量: {}", word_count);
}
在上述代码中:
- 首先定义了
StringExtensions
trait,其中声明了count_words
方法。 - 然后为
&str
类型实现了这个trait,在count_words
方法中通过split_whitespace
方法将字符串按空白字符分割,再用count
方法统计单词数量。 - 在
main
函数中创建了一个字符串并调用count_words
方法输出单词数量。
如果要为String
类型实现,只需将impl StringExtensions for &str
改为impl StringExtensions for String
,并在实现中通过&self
来访问字符串内容,实现逻辑与&str
类似。例如:
// 定义trait
trait StringExtensions {
fn count_words(&self) -> usize;
}
// 为String实现trait
impl StringExtensions for String {
fn count_words(&self) -> usize {
self.split_whitespace().count()
}
}
fn main() {
let s = String::from("Hello world Rust");
let word_count = s.count_words();
println!("单词数量: {}", word_count);
}