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

Provide ability to create getters that return A<&T> instead of &A<T> #78

Open
alopatindev opened this issue Sep 30, 2021 · 1 comment
Open
Labels

Comments

@alopatindev
Copy link

alopatindev commented Sep 30, 2021

Thanks for this awesome crate!

#[derive(Default, getset::Getters)]
struct A {
    #[get = "pub"]
    b: Option<B>,
}

#[derive(Default)]
struct B;

fn main() {
    let a = A::default();
    let b: Option<&B> = a.b();
}
error[E0308]: mismatched types
  --> src/main.rs:12:25
   |
12 |     let b: Option<&B> = a.b();
   |            ----------   ^^^^^
   |            |            |
   |            |            expected enum `Option`, found `&Option<B>`
   |            |            help: you can convert from `&Option<T>` to `Option<&T>` using `.as_ref()`: `a.b().as_ref()`
   |            expected due to this
   |
   = note:   expected enum `Option<&B>`
           found reference `&Option<B>`

Getters that return &Option<T> (just like &Result<T>, etc.) are not really useful, as they require getter user to pollute code with .as_ref() everywhere. As alternative, having manual trivial getters like

impl A {
    pub fn b(&self) -> Option<&B> {
        self.b.as_ref()
    }
}

is just another kind of boilerplate code pollution.

Can we do anything with this (and not some breaking change at the same time of course)?

I guess solution would likely require working with each such type separately (perhaps adding OptionGetters and #[get_option = "pub"], etc.), but still this would make this crate more coherent for users.

@mversic
Copy link

mversic commented May 28, 2022

I'd be happy to implement this as the default for Option<T> and/or Result<T, E>. Additionally, I would implement Vec<T> -> &[T], String -> &str. I cannot think of a reason why this would be preferred. This would be a breaking change though

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

3 participants