In Rust: what's the difference between clone() and to_owned() and when to use which?
Hello colleagues! I recently started learning Rust and I'm constantly confused about the clone() and to_owned() methods. They both seem to create a copy of data, but the documentation says they're different things. In practice, I see that clone() can be called on any type that implements the Clone trait, while to_owned() can only be called on types with the ToOwned trait. But isn't that the same thing?
Here's a specific example that confuses me:
```rust
let s: &str = "hello";
let a: String = s.to_owned();
let b: String = s.to_string(); // also works
// But why can't I write s.clone() to get a String?
// Because clone() returns &str, not String!
```
Another example: I'm working with slices. I have &[i32] and I want to get Vec. I can do slice.to_owned() — it works. But if I do slice
No answers yet.
Log in to leave an answer
Blogs
Working with Dates and Time in Java: Advanced Techniques and API
Concurrency and Multithreading in C++: From A to Z
Caching in PHP: Redis, Memcached, and Built-in Solutions from A to Z
Network Programming in C++: From Sockets to Asynchrony