Hacker News new | ask | show | jobs
by skitter 1119 days ago
The borrow checker rejects many otherwise valid programs. So if you do your job in correctly in C/C++, the borrow checker might accept the Rust equivalent or it might not.
1 comments

Maybe that was true in 2017, but today borrow checker and compiler in general has covered so much of the Rust design space that the "correct programs" it rejects are more like rejecting Duff's Device kind of code. You are more likely to find yourself implementing low-level data structure or device interface where you need raw pointers tightly localized in the unsafe{} scope.
It rejects anything it can't prove. Sometimes that proof is trivial for the programmer. Consider a string table. You intern by passing an owned String, the string table sticks it in a HashMap and gives you back a &str with a lifetime matching the table. From a C/C++ perspective, that's fine; Rust doesn't know that you'll never be removing things from that table, but you certainly can (and encapsulation can help you enforce that).

Since 2017 it certainly admits quite a few more programs, but it's still pretty easy to find things that require a different approach than they would in C or C++.

The article says that this code doesn't compile in 2023. Assuming the intention was to print "fox", I don't see how it is incorrect:

  let mut animal = "fox".to_string();
  let mut capture_animal = || {
      animal.push_str("es");
  };
  //ERROR:cannot borrow `animal` as immutable because it is also borrowed as mutable
  println!("Outside closure: {animal}");
  capture_animal();