Just for anyone wondering, no, that is not some obscure-but-valid Rust syntax. That's Rust-flavored gibberish.
EDIT: Shoot, I have mislead you all. Sorry, that could be valid code. Like so:
struct F<'a, T> {
ptr: &'a T,
__: String, // or any other type that implements Default
}
fn main() {
// The version seen above:
let ugly = F::<()> { ptr: &(), __: <_>::default() };
// A more readable version that does the same thing:
let better = F {
ptr: &(),
__: Default::default(),
};
}
It's intentionally ugly code—there's no reason to name a type F and a field __, or to throw explicit angle brackets all over the place like that—but it is valid.
...And your friend was entirely correct. Very sorry about that, without context I was reading that as a type definition, not a struct initialization. I've edited my comment.
There's a reason for it, although it's a little confusing. String is owned, ie you hold that memory directly . &str is borrowed, like you hold a pointer to it but not the memory itself, so you can't modify it or anything.
There are legitimate reasons for the distinction in Rust. &str is a pointer to some Unicode bytes somewhere in memory. String is an owned, growable buffer of Unicode bytes.
They work together. You can grab a &str reference to the contents of a String. You can allocate a String copy of a &str.
If a function just wants to read a string, you should pass it &str. The data stays where it is, and the function can look at it, without needing to make any copies. If you need to do string manipulation, or create a new string at runtime, you can allocate a new String. This lets you avoid a lot of unnecessary copying and allocation, and gives you control over how memory is used.
In JavaScript, "foo" is a string primitive, and new String("foo") is a string object. They work the same until they don't. There is literally no reason to ever intentionally use a string object and it will only cause you problems.
Oh I thought he was talking about Rust. But then I still don't see how what you've just described is similar to Rust - there's good reasons for all those String types
Rust makes a distinction between &str (a pointer to some Unicode bytes somewhere) and String (an owned, growable buffer of Unicode bytes). It's the difference between C++'s std::string_view and std::string. You can grab a &str reference to the contents of a String.
Because a String data type is dynamically sized, where a &str ‘s size is known at compile time. The two are very different and the difference is very useful
Edit: this actually isn’t the best way of describing this, see the replies
I don't think that's a very good way of describing it? Both String and &str are constant-sized structures that point to variably-sized strings. The difference is that String owns the buffer it's pointing to, and &str is just a reference to some bytes somewhere in memory.
The code basically says get the path of a file handle, convert it to utf-8, then copy it so it would be owned by the current scope while ignoring possibility of all errors (i.e. the program would crash if the filename included invalid Unicode codepoints or the file didn't exist or ...).
song.unwrap().unwrap() - I assume from this that song is something like an Option<Result<Song>>. Both those types have an unwrap() method, which means "I assert that this contains a valid item. Get it, or crash if I'm wrong." I'd move this onto a separate line.
.path() - Looks like the song provides a getter for its file Path. We are now definitely in the realm of std types.
.to_str() - Get a reference to the path's contents as a Unicode string. Since filepaths aren't necessarily valid Unicode, this returns Option<&str>.
.unwrap() - As before, "I assert that the path was made out of valid Unicode. Get the string, or crash if I am wrong."
.to_string() - Rust makes a distinction between &str (a reference to some Unicode bytes somewhere) and String (a growable owned vector of Unicode bytes). Using to_string() will allocate a new buffer and copy the str's bytes into it.
So, in short,
Do some unwrapping.
Get the song's path.
Assert that the path is valid Unicode.
Allocate a new string buffer and copy the path into it.
EDIT: Unless they have a specific reason to want a String specifically, I'd generally recommend using
let song = song.unwrap().unwrap();
let path = song.path().to_path_buf();
This will do almost exactly the same thing, but without asserting that the path is Unicode so that it can copy it into a new Unicode buffer. Instead, path will be a PathBuf; a filepath buffer. Path is to PathBuf as str is to String. 90% of the time, that would be better (won't crash on a non-Unicode file path, doesn't need to spend time scanning the path for Unicode errors.) All the file IO methods accept Path/PathBuf anyway.
IMO .to_owned() is better than .to_string(), because it tells what actually happens - converting a string to a string makes no sense, but converting to an owned value does. Some people prefer .into(), but I consider it being less readable
let path = song.unwrap().unwrap().path();
let path_string = path.to_str().unwrap().to_string();
Beyond that, it's hard to say with absolutely no context. Although, I suspect that the .to_str().unwrap().to_string() part might be removable or simplifiable. Right now it's asserting that the filepath is valid Unicode and copying it into a new buffer. With context, you could probably remove one or both of those steps.
That’s a joke. Rust has a ? operator that unwraps a Result if it’s Ok and returns from the function with the Err if it’s an error. Works for Option as well. The return type most be a Result, Option or Try(? not sure about this) for this to work. There’s an RFC called try blocks which will allow the usage of the ? operator in blocks as well
Rust is one of my main languages, but I really don't like these Option<Result<T>> types, or god forbid Option<Option<T>> or something like that. This seems like badly written library code, the same thing is in a mongodb driver crate. And also a programmer who respects himself should use the ? operator.
The secret about programming language preference is that they're often determined by which languages you had to work together with someone else on, who either didn't care or wasn't sufficiently skilled to write clean code.
When a new language comes onto the scene, the standards are slightly lower (because no one knows what looks good or bad in that language yet) and also there are very few examples of poorly written code in that language being popularized.
In the future, we'll have a whole bunch of terribly written rust and go, and that isn't a reflection on the quality of the language design really. Any language can be written horribly in.
The lsp suggests unwrap, I unwrap, lsp suggests to_str, I don't question. Blind faith. cargo check waiting around the corner with more errors than number of lines.
If you ask a Rust developer wtf this is they will write a 2-page-long essay explaining it and I still don't understand what Rust is and what it's used for
80
u/[deleted] Jan 25 '22
Why are
to_string()andto_str()two different things273
u/EquinoxRex Jan 25 '22
This is just haskell but written back to front
75
u/peaceknight05 Jan 25 '22
Image Transcription: Code
I'm a human volunteer content transcriber and you could be too! If you'd like more information on what we do and why we do it, click here!
131
u/TinyBreadBigMouth Jan 25 '22 edited Jan 25 '22
Let's analyze:
song.unwrap().unwrap()- I assume from this thatsongis something like anOption<Result<Song>>. Both those types have anunwrap()method, which means "I assert that this contains a valid item. Get it, or crash if I'm wrong." I'd move this onto a separate line..path()- Looks like the song provides a getter for its filePath. We are now definitely in the realm of std types..to_str()- Get a reference to the path's contents as a Unicode string. Since filepaths aren't necessarily valid Unicode, this returnsOption<&str>..unwrap()- As before, "I assert that the path was made out of valid Unicode. Get the string, or crash if I am wrong.".to_string()- Rust makes a distinction between&str(a reference to some Unicode bytes somewhere) andString(a growable owned vector of Unicode bytes). Usingto_string()will allocate a new buffer and copy the str's bytes into it.So, in short,
EDIT: Unless they have a specific reason to want a
Stringspecifically, I'd generally recommend usingThis will do almost exactly the same thing, but without asserting that the path is Unicode so that it can copy it into a new Unicode buffer. Instead,
pathwill be aPathBuf; a filepath buffer.Pathis toPathBufasstris toString. 90% of the time, that would be better (won't crash on a non-Unicode file path, doesn't need to spend time scanning the path for Unicode errors.) All the file IO methods acceptPath/PathBufanyway.16
u/FranticBronchitis Jan 25 '22
Ah yes,
Spotifylibrespot Wrapped13
u/InsertMyIGNHere Jan 25 '22
Please just press enter at least once I promise nothing bad happens
53
u/aeropl3b Jan 25 '22
Rust: You will right really good code
Also Rust ^
23
u/SueedBeyg Good code makes sense. Bad code just works. Yours does neither. Jan 25 '22
When it’s not compiling and you have no idea why
One more unwrap should do it
7
u/[deleted] Jan 25 '22
Merry Christmas?
7
u/iamalicecarroll Jan 26 '22
IMO
.to_owned()is better than.to_string(), because it tells what actually happens - converting a string to a string makes no sense, but converting to an owned value does. Some people prefer.into(), but I consider it being less readable6
u/kurosaur Jan 26 '22
"The compiler told me to!"
5
u/[deleted] Jan 25 '22
Yes this is a meme but what is the real solution to this?
4
u/MyAntichrist Jan 26 '22
That code is a lot to unwrap.
3
u/rustyredditortux Jan 26 '22
this isn't bad rust code
1
u/Budgiebrain222 Jan 26 '22 edited Jan 26 '22
Please for the love of God spread these variables over multiple lines.
Using this also works:
I don't really understand why you're turning a path variable to a mutable string than to an immutable string though
3
u/timleg002 Jan 26 '22
Rust is one of my main languages, but I really don't like these
Option<Result<T>>types, or god forbidOption<Option<T>>or something like that. This seems like badly written library code, the same thing is in a mongodb driver crate. And also a programmer who respects himself should use the?operator.1
u/DizzySkin Jan 26 '22
The secret about programming language preference is that they're often determined by which languages you had to work together with someone else on, who either didn't care or wasn't sufficiently skilled to write clean code.
When a new language comes onto the scene, the standards are slightly lower (because no one knows what looks good or bad in that language yet) and also there are very few examples of poorly written code in that language being popularized.
In the future, we'll have a whole bunch of terribly written rust and go, and that isn't a reflection on the quality of the language design really. Any language can be written horribly in.
1
u/[deleted] Jan 26 '22
I love rust but this is ridiculous
1
u/pikaynu Jan 26 '22
The lsp suggests
unwrap, I unwrap, lsp suggeststo_str, I don't question. Blind faith.cargo checkwaiting around the corner with more errors than number of lines.1
u/[deleted] Jan 26 '22
average ? ignorer
1
u/RolyBoy Jan 30 '22
Have you ever heard about the Demeter law lol
1
u/Huizengek Feb 01 '22
If you ask a Rust developer wtf this is they will write a 2-page-long essay explaining it and I still don't understand what Rust is and what it's used for
-13
u/Knuffya Jan 25 '22
rust geh c++ maester rece
0
u/[deleted] Feb 01 '22
[deleted] — view deleted comment