|
| 1 | +# `Cow` π aka `Copy on write` |
| 2 | + |
| 3 | + <span class="speech-bubble"> Let's talk about `Cow` π aka `Copy on write`</span> |
| 4 | + |
| 5 | +```rust,editable |
| 6 | +use std::borrow::Cow; |
| 7 | +
|
| 8 | +fn main() { |
| 9 | + println!("πΈπ¨ Welcome to the Farm (and Alien Abduction) Fun Zone! π\n"); |
| 10 | +
|
| 11 | + // --- π Our First Cow: Just Grazing Peacefully --- |
| 12 | + // This cow is just chillin' in the field, like a borrowed string. |
| 13 | + let mut peaceful_cow: Cow<'static, str> = Cow::Borrowed("Mooo, just grazing... πΏ"); |
| 14 | + println!("1. Peaceful Cow: {}", peaceful_cow); |
| 15 | + println!(" (It's borrowed! Just observing this cow. π§)\n"); |
| 16 | +
|
| 17 | + // --- π½ UFO Appears! Time to SUCK the Cow! --- |
| 18 | + // The UFO wants to "modify" the cow (i.e., abduct it!). |
| 19 | + // If it's a borrowed cow, the UFO needs to make its OWN copy to take! |
| 20 | + // (This simulates `to_mut()` forcing a copy for modification) |
| 21 | + println!("2. OH NO! A UFO appears! π½"); |
| 22 | + peaceful_cow.to_mut().push_str(" AIEEEE! I'm being beamed up! β¬οΈ"); |
| 23 | + println!(" Cow after abduction attempt: {}", peaceful_cow); |
| 24 | + println!(" (Since it was borrowed, the UFO made a *copy* to abduct. The original is safe... for now! π)\n"); |
| 25 | +
|
| 26 | +
|
| 27 | + // --- π Our Second Cow: Already in Its Own Barn --- |
| 28 | + // This cow is already "owned" by us, like an owned String. |
| 29 | + let mut owned_cow: Cow<'_, str> = Cow::Owned(String::from("Mooo, I'm safe in MY barn! π‘")); |
| 30 | + println!("3. Owned Cow: {}", owned_cow); |
| 31 | + println!(" (This cow is already owned! No initial copy needed. π)\n"); |
| 32 | +
|
| 33 | + // --- π½ UFO Appears AGAIN! --- |
| 34 | + // The UFO wants to abduct THIS cow too! |
| 35 | + // But since this cow is *already owned*, the UFO can just grab *this specific cow*. |
| 36 | + // No new copy is needed because it's already "owned" for modification. |
| 37 | + println!("4. Another UFO! This one's persistent! πΈ"); |
| 38 | + owned_cow.to_mut().push_str(" Help! They're taking MY barn too! π΅βπ«"); |
| 39 | + println!(" Owned Cow after abduction: {}", owned_cow); |
| 40 | + println!(" (It was already owned, so the UFO just took *that* cow. Efficient abduction! π―)\n"); |
| 41 | +
|
| 42 | + println!("πΈππ¨ CoW: Keeping your original data safe from alien abduction, unless they need to make a copy! β¨"); |
| 43 | +} |
| 44 | +``` |
| 45 | + |
| 46 | +> π‘ You can read more about `Cow` here π [6 things you can do with the Cow π in Rust π¦](https://dev.to/kgrech/6-things-you-can-do-with-the-cow-in-rust-4l55) |
0 commit comments