3 ms·
Curious about the following lines [1] [2]: let processes = procfs::process::all_processes().unwrap(); ... let process = p.unwrap(); Doesn't this u
by jraph 4y ago
Curious about the following lines [1] [2]:
let processes = procfs::process::all_processes().unwrap();
...
let process = p.unwrap();
Doesn't this use of unwrap cancel out one of the advantages of Rust which is to handle errors quite comprehensively?
Here process could be null, and we try to access it the line after.
edit: actually process won't be null, unwrap will panic. Got it. I still think a good error message would be better than exposing the user to a crash, but that's a matter of opinion. It seems like the whole point of using Rust, and also of such a tool, is to be robust and user-friendly (since it implements an UNIX one liner), and an unhandled crash could lower the confidence of the user in the tool.
[1] https://github.com/jkfran/killport/blob/3a43d037c08ab3aec730dbb66cb6642b873296b2/src/linux.rs#L81 https://github.com/jkfran/killport/blob/3a43d037c08ab3aec730...
[2] https://github.com/jkfran/killport/blob/3a43d037c08ab3aec730dbb66cb6642b873296b2/src/linux.rs#L85 https://github.com/jkfran/killport/blob/3a43d037c08ab3aec730...
- TheDong 4y agoLet's say that you're unable to list all processes. What do you do to handle that error? You exit the program. What does unwrap do? It safely exits the program. Seems to be handling the error just fine to me. The only downside is that the error message won't look great, but for a tool like this, that seems fine. > Here process could be null, and we try to access it the line after. Process cannot be null. Rust does not have nulls outside of unsafe code. The type of 'p' there is 'Result<Process, ProcError>', and so 'process' is of type 'Process', which cant' be null. That's one of the actual benefits of rust: it is memory safe outside of unsafe code, and doesn't make the "null" mistake.
- deleted 4y ago[deleted]
- FpUser 4y ago>"Let's say that you're unable to list all processes. What do you do to handle that error? You exit the program." No, you list what you can and give meaningful error message for any particular offenders.
- diarrhea 4y ago`expect` can be used instead of `unwrap` to print an error. That's quite idiomatic I'd say for situations where there's no way to recover anyway, as you mention.
- scottlamb 4y agoI'd say `expect` is idiomatic for situations in which the error is due to an unrecoverable logic flaw. If it's due to user error, I'd want to do something else just to customize the error message format. Also, as another commenter mentioned, the `let process = p.unwrap()` is suspicious. I imagine this can happen if a process simply exits between being returned from the `/proc` traversal and `opendir("/proc/<pid>")`. If the error is `ENOENT`, it should simply continue to the next pid without printing an error at all.