Rust

Rust

By DeepSource

Found occurrence of Rc<String> RS-W1064

Anti-pattern

Rc<String> is unnecessary and adds another level of indirection. A String is already a pointer to heap data. Consider using Rc<str>.

Rc<T> only allows mutation when no other references to Rc<T> exist. This makes Rc<String> a read-only pointer to a String, unless the reference is exclusive. If you need a read-only shared string, consider using a str slice instead.

Editing Rc<str> requires you to create a new Rc<str>, as compared to being able to use Rc::get_mut() with Rc<String>.

Examples

Bad practice

let mut foo: Rc<String> = Rc::new("hello".to_string());
Rc::get_mut(&mut foo).get(|f| f.push_str(", world!"));
assert_eq!(foo.as_str(), "hello, world!");

Recommended

let mut foo: Rc<str> = Rc::from("hello");
foo = Rc::from("hello, world!");
assert_eq!(foo.as_ref(), "hello, world!");