AsRef<T> 是一个通用的 Trait,用于从某种类型“借用”一个引用,U: AsRef<T> 表示 U 类型可以转换成 &T.例如,AsRef<str> 可以接收 str, String 类型,并转换成 &str

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
// Obtain the number of bytes (not characters) in the given argument.
fn byte_counter<T>(arg: T) -> usize where T: AsRef<str> {
arg.as_ref().as_bytes().len()
}

// Obtain the number of characters (not bytes) in the given argument.
fn char_counter<T>(arg: T) -> usize where T: AsRef<str> {
arg.as_ref().chars().count()
}

// =================
// ===== TESTS =====
// =================
#[test]
fn different_counts() {
let s = "Café au lait";
assert_ne!(char_counter(s), byte_counter(s));
}

#[test]
fn same_counts() {
let s = "Cafe au lait";
assert_eq!(char_counter(s), byte_counter(s));
}

#[test]
fn different_counts_using_string() {
let s = String::from("Café au lait");
assert_ne!(char_counter(s.clone()), byte_counter(s));
}

#[test]
fn same_counts_using_string() {
let s = String::from("Cafe au lait");
assert_eq!(char_counter(s.clone()), byte_counter(s));
}

AsMut<T>AsRef<T> 的可变版本,U: AsMut<T> 表示 U 类型可以转换成 &mut T(当然 U 也得是 &mut 或者 owned 的)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// Squares a number using as_mut().
fn num_sq<T>(arg: &mut T) where T: AsMut<u32> {
let value = arg.as_mut();
*value *= *value;
}

// =================
// ===== TESTS =====
// =================
#[test]
fn mult_box() {
let mut num: Box<u32> = Box::new(3);
num_sq(&mut num);
assert_eq!(*num, 9);
}