borrowed.rs 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. /*
  2. Dioxus manages borrow lifetimes for you. This means any child may borrow from its parent. However, it is not possible
  3. to hand out an &mut T to children - all props are consumed by &P, so you'd only get an &&mut T.
  4. How does it work?
  5. Dioxus will manually drop closures and props - things that borrow data before the component is ran again. This is done
  6. "bottom up" from the lowest child all the way to the initiating parent. As it traverses each listener and prop, the
  7. drop implementation is manually called, freeing any memory and ensuring that memory is not leaked.
  8. We cannot drop from the parent to the children - if the drop implementation modifies the data, downstream references
  9. might be broken since we take an &mut T and and &T to the data. Instead, we work bottom up, making sure to remove any
  10. potential references to the data before finally giving out an &mut T. This prevents us from mutably aliasing the data,
  11. and is proven to be safe with MIRI.
  12. */
  13. use dioxus::prelude::*;
  14. fn main() {
  15. dioxus::desktop::launch(app);
  16. }
  17. fn app(cx: Scope) -> Element {
  18. let text = cx.use_hook(|_| vec![String::from("abc=def")]);
  19. let first = text.get_mut(0).unwrap();
  20. cx.render(rsx! {
  21. div {
  22. Child1 {
  23. text: first
  24. }
  25. }
  26. })
  27. }
  28. #[derive(Props)]
  29. struct C1Props<'a> {
  30. text: &'a mut String,
  31. }
  32. fn Child1<'a>(cx: Scope<'a, C1Props<'a>>) -> Element {
  33. let (left, right) = cx.props.text.split_once("=").unwrap();
  34. cx.render(rsx! {
  35. div {
  36. Child2 { text: left }
  37. Child2 { text: right }
  38. }
  39. })
  40. }
  41. #[derive(Props)]
  42. struct C2Props<'a> {
  43. text: &'a str,
  44. }
  45. fn Child2<'a>(cx: Scope<'a, C2Props<'a>>) -> Element {
  46. cx.render(rsx! {
  47. Child3 {
  48. text: cx.props.text
  49. }
  50. })
  51. }
  52. #[derive(Props)]
  53. struct C3Props<'a> {
  54. text: &'a str,
  55. }
  56. fn Child3<'a>(cx: Scope<'a, C3Props<'a>>) -> Element {
  57. cx.render(rsx! {
  58. div { "{cx.props.text}"}
  59. })
  60. }