2 ms·
Let's have some fun with the article's example: pub fn read<P: AsRef<Path>>(path: P) -> io::Result<Vec<u8>> { fn inner(path: &Path) -> io::Result<Vec
by WalterBright 4y ago
Let's have some fun with the article's example:
pub fn read<P: AsRef<Path>>(path: P) -> io::Result<Vec<u8>> {
fn inner(path: &Path) -> io::Result<Vec<u8>> {
let mut file = File::open(path)?;
let mut bytes = Vec::new();
file.read_to_end(&mut bytes)?;
Ok(bytes)
}
inner(path.as_ref())
}
In D (I'm not a Rust expert, so apologies for inevitable mistakse):
public io.Result!(ubyte[]) read(P : Path)(ref P path) {
io.Result!(ubyte[]) inner(ref Path path) {
auto file = File.open(path);
auto bytes = file.read_to_end();
return Ok(bytes);
}
inner(path);
}
- deleted 4y ago[deleted]
- boxed 4y agoPutting the return type to the left of the function name is pretty bad. So C/C++/D loses quite a bit on that at least...
- LegionMammal978 4y agoSome nitpicks, since you're almost asking for them: 'read' taking 'ref P path' isn't entirely accurate. In Rust, 'path' is moved into the 'read' function, which destroys it after calling 'inner'. (If the caller doesn't want it to be destroyed, it provides a reference, i.e., a safe non-null immutable pointer; when 'read' destroys the reference, nothing happens.) As I understand it, 'ref P path' in D still gives the caller the ability to access 'path' after calling 'read' and the responsibility for destroying it. Also, the '?'s are important for error handling: the 'File::open()?' line basically expands to let mut file; match File::open(path) { Ok(value) => { file = value; } Err(error) => { return Err(error); } } and similar for the 'read_to_end()?', except the result is discarded. And one of the reasons (apart from flexibility) that 'read_to_end()' takes an external vector as input is so that the caller can retain the result of a partial read; otherwise, the function would have to return a vector on error as well as on success.
- WalterBright 4y agoI understand that Rust has somewhat different semantics, but for purposes of illustration I focused on the syntax. For example, D could would likely throw an exception, rather than use pattern matching, for error handling.