digitalmars.D.learn - Enforce not null at compile time?
- Antonio (2/2) Jun 20 2022 Is there any way to specify that a variable, member or parameter
- Dennis (8/10) Jun 20 2022 Depends on the type. Basic types can't be null. Pointers and
- max haughton (4/6) Jun 20 2022 You can use an invariant if it's a member of an aggregate but be
- Antonio (12/18) Jun 20 2022 I'm using preconditions when calling functions
Is there any way to specify that a variable, member or parameter can't be null?
Jun 20 2022
On Monday, 20 June 2022 at 17:48:48 UTC, Antonio wrote:Is there any way to specify that a variable, member or parameter can't be null?Depends on the type. Basic types can't be null. Pointers and classes can always be `null`, though you could wrap them in a custom library type that doesn't allow them to be `null`. Dynamic arrays and associative arrays can be null, but it's equivalent to them being empty, so you can still use them like normal. You can pass a struct as a `ref` parameter, which passes it by reference but it's still typed as a plain struct, so it can't be `null`.
Jun 20 2022
On Monday, 20 June 2022 at 17:48:48 UTC, Antonio wrote:Is there any way to specify that a variable, member or parameter can't be null?You can use an invariant if it's a member of an aggregate but be warned that these are only checked at the boundaries of public member functions.
Jun 20 2022
On Monday, 20 June 2022 at 19:08:32 UTC, max haughton wrote:On Monday, 20 June 2022 at 17:48:48 UTC, Antonio wrote:I'm using preconditions when calling functions ```d auto readByCredentiasl(CredentialsDTO credentials) in (credentials !is null) in (credentias.username !is null) ... { ... } ``` But it's runtime validation, not formally validated by compiler.Is there any way to specify that a variable, member or parameter can't be null?You can use an invariant if it's a member of an aggregate but be warned that these are only checked at the boundaries of public member functions.
Jun 20 2022