Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[FEATURE REQUEST] downcast/upcast on Option<Object> #842

Closed
ranfdev opened this issue Dec 1, 2022 · 5 comments · Fixed by #843
Closed

[FEATURE REQUEST] downcast/upcast on Option<Object> #842

ranfdev opened this issue Dec 1, 2022 · 5 comments · Fixed by #843
Labels
enhancement New feature or request

Comments

@ranfdev
Copy link
Member

ranfdev commented Dec 1, 2022

There are many cases where gtk returns an Option<Widget> which must be downcasted.
Doing let label: gtk::Label = list_item.child().unwrap().downcast().unwrap(); is not fun (note: child() returns Option<Widget>).

Implementing downcast and upcast for Option<Widget> would remove an unwrap.
I think it makes sense. In OOP languages you can have null objects, and null objects can be downcasted to null subclassess, can't they? (Edit: in Java you can upcast a null, but not downcast it. In any case, if we return a Result when downcasting, everything is alright)

@ranfdev ranfdev added the enhancement New feature or request label Dec 1, 2022
@sdroege
Copy link
Member

sdroege commented Dec 1, 2022

How about let label = list_item.child().and_then(|c| child.downcast::<gtk::Label>().ok()).unwrap()?

@ranfdev
Copy link
Member Author

ranfdev commented Dec 1, 2022

That's even longer than before

@ranfdev
Copy link
Member Author

ranfdev commented Dec 1, 2022

// current
let label: gtk::Label = list_item.child().unwrap().downcast().unwrap();
// your solution
let label = list_item.child().and_then(|c| c.downcast::<gtk::Label>().ok()).unwrap()
// with downcast on Option<Object>
let label: gtk::Label = list_item.child().downcast().unwrap();

@bilelmoussaoui
Copy link
Member

This is a duplicate of #497

@sdroege
Copy link
Member

sdroege commented Dec 1, 2022

I don't know, the and_then() solution seems most Rust-y to me. But give it a try if you can implement it on Option in a way that behaves well :)

ranfdev added a commit to ranfdev/gtk-rs-core that referenced this issue Dec 1, 2022
bilelmoussaoui pushed a commit that referenced this issue Dec 4, 2022
* Add CastNone trait

Closes #842

* Add CastNone to prelude, add dynamic_cast

* Add example for CastNone

* Describe type using turbofish op
bilelmoussaoui pushed a commit that referenced this issue Dec 5, 2022
* Add CastNone trait

Closes #842

* Add CastNone to prelude, add dynamic_cast

* Add example for CastNone

* Describe type using turbofish op
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

Successfully merging a pull request may close this issue.

3 participants