Hacker News new | past | comments | ask | show | jobs | submit login

> Callbacks by definition create multiple paths to the data.

How come, when you have a struct method, accessing field members only visible to that specific method.

Something that is very easy to do with moving in lambda contexts in C++.




Because the closure itself contains a reference either to the struct or to its fields. That's the second path, and it can be invalidated by the first path either a) freeing the struct or b) changing its "shape" in memory (resizing a `Vec`, changing enum variants, etc.)

You can alternatively move the struct or its fields into the closure, but then you lose the first path. I know you're not doing that because if you were you wouldn't be having lifetime problems (and you wouldn't be able to share the state across event handlers, so it's not a great solution anyway).


The quoted sentence is not true, but most practical callbacks will create multiple paths to objects via borrows. Or you can move your structs into closures (like in C++). But I think what you originally wrote (using callbacks without Rc/RefCell) is fundamentally hard. You have to guarantee somehow that the struct is still alive when you access it though the borrow in the callback, otherwise you have a memory safety problem.


The situation I was having issues is explicitly acknowledged by the NLL RFC as being an issue.

It is related to closure desugaring.

https://github.com/nikomatsakis/nll-rfc/blob/master/0000-non...




Consider applying for YC's Summer 2025 batch! Applications are open till May 13

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: