this post was submitted on 21 Jul 2023
3 points (80.0% liked)

Rust

6113 readers
7 users here now

Welcome to the Rust community! This is a place to discuss about the Rust programming language.

Wormhole

[email protected]

Credits

  • The icon is a modified version of the official rust logo (changing the colors to a gradient and black background)

founded 2 years ago
MODERATORS
 

crosspostato da: https://lemmy.world/post/1916287

Hi everybody, I'm new to Rust.

So, I have a struct Panel which contains a data widget which implements the trait Widget I have to implement a function for Panel that uses another function that requires a type that implements Widget.

I tried Box<T>, Rc<T>, Box<dyn Widget, &T, but nothing, always compiler errors.

How can I fix this?

top 7 comments
sorted by: hot top controversial new old
[–] [email protected] 2 points 1 year ago (1 children)

Use self.widget?

Maybe show some code of what you're trying to do.

[–] djtech 1 points 1 year ago (3 children)

Yes, obviously, but there are de-referincing/borrwowing/trait problem.

If you want to check the Trait: https://docs.rs/ratatui/latest/ratatui/widgets/trait.Widget.html

If you want to check what function do I need to run: https://docs.rs/ratatui/latest/ratatui/terminal/struct.Frame.html#method.render_widget

So the struct is something like struct Panel<T: Widget> { data: T } (tried also with Box, Rc, &mut T and Box

I need to implement a method for Panel which simply uses the function linked above. (so just asks for a Frame, the Rect type is generated by my other function)

[–] [email protected] 3 points 1 year ago (1 children)

That function takes ownership of the Widget, there's no borrowing here. Maybe that's the problem, that you're passing a reference instead of the actual object?

So, if you have a Panel containing the Widget, the function you're calling render_widget in has to take self, not &self or &mut self.

Alternatively, you can use data: Option<T> in Panel, let the function take &mut self and then use self.data.take() to move it out of self.

[–] djtech 2 points 1 year ago

I checked the code and noticed that I wrote &self as the parameter 🤦🏻

Now everything works. Thanks man

[–] [email protected] 1 points 1 year ago

Showing the code and the errors compiler gives to you would help a bunch.

[–] akash_rawal 1 points 1 year ago

Seems like data: T or data: &'a mut T should work for you. Your function should be accepting mut self or &mut self.

[–] [email protected] 1 points 1 year ago

The first problem I saw is that Widget::render takes self by value, meaning that the widget will be destroyed after being rendered once. The need to satisfy that method's type could be the cause of the other errors you're running into.