4 ms·
String in Rust is very similar to std::string in C++, while str is std::string_view except it is safe to use. StringBuffer in Java is not like String in Rust.
by _0w8t 4y ago
String in Rust is very similar to std::string in C++, while str is std::string_view except it is safe to use.
StringBuffer in Java is not like String in Rust. In particular, one cannot pass StringBuffer in Java to a function taking String, while both Rust and C++ allow to implicitly convert the string backed by a heap into the corresponding read-only view.
- sirwhinesalot 4y agoStrings in Java own their memory, they aren't views, they're closer to Box<str>. That's why you can't implicitly convert a StringBuilder into one. I know this, I'm not the one you need to explain it too, it's Rust newbies. So many problems would have been avoided with Str/StrBuf or StrView/Str, but now the ship has sailed.
- rrobukef 4y agoString in Java share their memory with other substrings of the same allocation. They are views.
- cesarb 4y agoIIRC, that used to be the case, but recent Java releases changed it so that memory is no longer shared with substrings. The former behavior could cause some extreme memory leaks (unless you were very careful to always manually duplicate each substring); a one-character substring could keep a multi-megabyte memory allocation alive. See for instance https://stackoverflow.com/questions/33893655/string-substring-making-a-copy-of-the-underlying-char-value https://stackoverflow.com/questions/33893655/string-substrin... which discusses this issue.
- masklinn 4y agoThat was changed years ago (the slicing optimisation was removed in Java 7 or something) because it caused too many memory leaks. It was also a (bad) optimisation, it was never part of the langage model or semantics.
- kevincox 4y agoBut why is it &str not StringView? The main reason I see is that the lifetimes are more natural as &'a str instead of StringView<'a>. I don't think this inconsistency is worth it. It is really just a hack that reinterpretes the (vtable, ptr) of an unsized type as (len, ptr). The only other type that does this are slices. Or maybe the real reason is that Rust can't be generic over lifetimes, so you would need StringView and StringViewMut. But even that it doesn't seem like a huge deal to me for a simpler "language" (my understanding is that these hacks are actually done in std, but it's been a while since I looked at the code).
- MrBuddyCasino 4y agoThey added CharSequence interface to address this, both StringBuilder and String implement it. Its not widely used though.