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

Rust like Default Trait for Dart? #2122

Open
18601673727 opened this issue Feb 20, 2022 · 3 comments
Open

Rust like Default Trait for Dart? #2122

18601673727 opened this issue Feb 20, 2022 · 3 comments
Labels
request Requests to resolve a particular developer problem

Comments

@18601673727
Copy link

Given following rust code:

#[derive(Default)]
struct MyStructure {
    id: usize,
    name: String,
}

So that MyStructure.id would be 0 and MyStructure.name would be "" by default.
Wonder if there was something equivalent to this approach/suger in Dart?

@18601673727 18601673727 added the request Requests to resolve a particular developer problem label Feb 20, 2022
@mnordine
Copy link
Contributor

This seems to be achievable with the upcoming macros language feature:

@default
class MyClass {
  int id;
  String name;
}

could desugar to:

class MyClass {
  int id = 0;
  String name = '';
}

@18601673727
Copy link
Author

@mnordine Thanks a lot!

@Levi-Lesches
Copy link

Note that you can just write the regular class with their defaults today, as @mnordine said. You can also put the defaults in the constructor for slightly more control.

class MyClass {
  int? id;
  String? name;

  MyClass.allNull({this.id, this.name});  // leaves fields null if not given a value

  MyClass.nonNull({this.id = 0, this.name = "");  // will give every field a default
}

Does that answer your request?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
request Requests to resolve a particular developer problem
Projects
None yet
Development

No branches or pull requests

3 participants