Improve from_into.rs #2282
Replies: 1 comment
-
|
Hi there! This is a very common point of confusion when starting with Rust. Your logic of "not throwing away valid information" is noble, but it goes against one of Rust's core philosophies: Be explicit, not speculative. The tests expect you to return the default Person if any part of the parsing fails because of how the From<&str> trait is being utilized in this specific exercise. Here is why your initial approach tripped the tests: The Contract of the Instruction: Usually, in these exercises, if the input string doesn't strictly match the expected CSV-like format (name,age), the entire conversion is considered "invalid" rather than "partially valid." Predictability: If I pass an empty string or a broken age, getting a "half-default" person can lead to silent bugs later in a real application. Rust prefers you to either succeed completely or fail (and return a standard default to signal that the input was not processable). To pass the tests while keeping your code clean, you should check for the empty name and the parse result before building the struct. Here is the "intended" way to handle it for this exercise: The key takeaway is: If the input is malformed, don't try to salvage it with partial defaults unless the documentation explicitly tells you to. Hope this helps you clear the exercise! |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
I failed these tests initially, but when I looked at them, I realized that a reasonable interpretation of the instructions would produce different results.
Specifically, the tests
test_bad_age,test_missing_age, andtest_missing_nameare not testing the behavior that I inferred from the instructions. I understood the instruction (4) to be "If the name is empty, return [a Person with the default name]" and (6) to be "If parsing the age fails, return [a Person with the default age]".The reason my brain immediately jumped to this incorrect conclusion is that the context makes it clear that, in such a case, it's possilbe the rest of the information is valid--so why throw away valid information?
I don't think the tests or instructions are wrong, only that they could be clearer (or better).
For reference, here is what my initial implementation looked like:
Beta Was this translation helpful? Give feedback.
All reactions