Commit 0eea69f
committed
// cow1.rs
//
// This exercise explores the Cow, or Clone-On-Write type. Cow is a
// clone-on-write smart pointer. It can enclose and provide immutable access to
// borrowed data, and clone the data lazily when mutation or ownership is
// required. The type is designed to work with general borrowed data via the
// Borrow trait.
//
// This exercise is meant to show you what to expect when passing data to Cow.
// Fix the unit tests by checking for Cow::Owned(_) and Cow::Borrowed(_) at the
// TODO markers.
//
// Execute `rustlings hint cow1` or use the `hint` watch subcommand for a hint.
// I AM NOT DONE
use std::borrow::Cow;
fn abs_all<'a, 'b>(input: &'a mut Cow<'b, [i32]>) -> &'a mut Cow<'b, [i32]> {
for i in 0..input.len() {
let v = input[i];
if v < 0 {
input.to_mut()[i] = -v;
}
}
input
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn reference_mutation() -> Result<(), &'static str> {
let slice = [-1, 0, 1];
let mut input = Cow::from(&slice[..]);
match abs_all(&mut input) {
Cow::Owned(_) => Ok(()),
_ => Err("Expected owned value"),
}
}
#[test]
fn reference_no_mutation() -> Result<(), &'static str> {
let slice = [0, 1, 2];
let mut input = Cow::from(&slice[..]);
match abs_all(&mut input) {
Cow::Borrowed(_) => Ok(()), // 无修改,保持借用状态
_ => Err("Expected borrowed value"),
}
}
#[test]
fn owned_no_mutation() -> Result<(), &'static str> {
let slice = vec![0, 1, 2];
let mut input = Cow::from(slice);
match abs_all(&mut input) {
Cow::Owned(_) => Ok(()), // 原本就是自有数据,无修改仍保持自有
_ => Err("Expected owned value"),
}
}
#[test]
fn owned_mutation() -> Result<(), &'static str> {
let slice = vec![-1, 0, 1];
let mut input = Cow::from(slice);
match abs_all(&mut input) {
Cow::Owned(_) => Ok(()), // 自有数据修改后仍为自有
_ => Err("Expected owned value"),
}
}
}1 parent 9ea72ed commit 0eea69f
1 file changed
+6
-12
lines changed| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
20 | 20 | | |
21 | 21 | | |
22 | 22 | | |
23 | | - | |
24 | 23 | | |
25 | 24 | | |
26 | 25 | | |
| |||
33 | 32 | | |
34 | 33 | | |
35 | 34 | | |
36 | | - | |
37 | 35 | | |
38 | 36 | | |
39 | 37 | | |
| |||
44 | 42 | | |
45 | 43 | | |
46 | 44 | | |
47 | | - | |
48 | 45 | | |
49 | 46 | | |
50 | 47 | | |
51 | | - | |
| 48 | + | |
| 49 | + | |
52 | 50 | | |
53 | 51 | | |
54 | 52 | | |
55 | 53 | | |
56 | 54 | | |
57 | | - | |
58 | | - | |
59 | | - | |
60 | 55 | | |
61 | 56 | | |
62 | 57 | | |
63 | | - | |
| 58 | + | |
| 59 | + | |
64 | 60 | | |
65 | 61 | | |
66 | 62 | | |
67 | 63 | | |
68 | 64 | | |
69 | | - | |
70 | | - | |
71 | | - | |
72 | 65 | | |
73 | 66 | | |
74 | 67 | | |
75 | | - | |
| 68 | + | |
| 69 | + | |
76 | 70 | | |
77 | 71 | | |
78 | 72 | | |
0 commit comments