2 ms·
My rules of thumb for Rust, that for the most part keep me out of allocation puzzles, are: - Never combine two things that can be valid for different amounts o
by whatshisface 4y ago
My rules of thumb for Rust, that for the most part keep me out of allocation puzzles, are:
- Never combine two things that can be valid for different amounts of time into one struct. For example: A file struct should not contain both information about how it is formatted, which is true forever and can be used for many files, and a file handle, which could be invalidated by the OS at any time. Breaking this rule will fill your code with Box/Arc as you try to imitate classical OOP.
- Don't be afraid to frequently pass contextual information to functions; you don't need to put everything that will remain the same between two calls into `self`. For example, every function that works with the file can take the file handle and the format information as separate arguments. Trying to DRY function arguments by combining data with different lifetimes into a single struct and then hiding that argument in the `self` parameter might feel like simplification, but in Rust it triggers the above problem.
- Functions that call functions that take mutable references as output locations should do the same, unless they have to allocate for another reason. This rule of thumb will tend to push allocation as far outside of loops as possible.
With these in hand, I almost never need to box or reference count anything. If you fail to heed the fact that Rust is not really an OOP language, your entire program will start to look like the hairy parts of C libraries that interface with the Python interpreter.
- ssokolow 4y ago> If you fail to heed the fact that Rust is not really an OOP language, your entire program will start to look like the hairy parts of C libraries that interface with the Python interpreter. Any tips for those of us who see PyO3 as one of Rust's biggest killer apps? (Honest question. I hate how unmaintainable Python is but I don't know of any better equivalent to PyQt/PySide's memory-safe QWidget bindings or the RAD-friendly ORM migrations in Django ORM or SQLAlchemy+Alembic.)
- whatshisface 4y agoI imagine it would go like writing a good C library for Python, where the PyResult<> wrappers disappear as you move deeper into your code and away from the interface. Hopefully working with Python objects on the outside won't require using references everywhere on the inside.
- ssokolow 4y agoAhh, so more or less what I'm doing. Design the Rust code as if it's going to be a generic C library with bindings for multiple languages and then write a PyO3 binding layer that just clones however much is necessary to convert until it's proven that more optimization is needed.