# Request: IsZero trait and #\[derive(IsZero)\]

**URL:** <https://internals.rust-lang.org/t/request-iszero-trait-and-derive-iszero/12636>\
**Category:** language design\
**Created:** [June 27, 2020, 2:56am UTC](https://internals.rust-lang.org/t/request-iszero-trait-and-derive-iszero/12636 "2020-06-27T02:56:42Z")\
**Posts on this page:** 20\
**Page:** 1

<div class="post-metadata">

**Author:** ![KSXGitHub](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/ksxgithub/32/5582_2.png) [@KSXGitHub](https://internals.rust-lang.org/u/KSXGitHub)\
**Post date:** [June 27, 2020, 2:56am UTC](https://internals.rust-lang.org/t/request-iszero-trait-and-derive-iszero/12636/1 "2020-06-27T02:56:42Z")

</div>

## My situation

When I use `serde` to serialize/deserialize data, I want to skip serializing empty fields. I do this:

```rust
#[derive(Default, Serialize, Deserialize)]
struct MyData {
  pub mandatory_field: i32,
  #[serde(default, skip_serializing_if = "String::is_empty")]
  pub optional_string: String,
  #[serde(default, skip_serializing_if = "Vec::is_empty")]
  pub optional_array: Vec<i32>,
  #[serde(default, skip_serializing_if = "Option::is_none")]
  pub optional_value: Option<i32>,
}

```

It is manageable with built-in data structures, but with custom types, I have to make my own `is_empty`:

```rust
#[derive(Default, Serialize, Deserialize)]
struct MyData {
  pub mandatory_field: i32,
  #[serde(default, skip_serializing_if = "OptionalData::is_empty")]
  pub optional_data: OptionalData,
}

#[derive(Default, Serialize, Deserialize)]
struct OptionalData {
  #[serde(default, skip_serializing_if = "String::is_empty")]
  pub optional_string: String,
  #[serde(default, skip_serializing_if = "Vec::is_empty")]
  pub optional_array: Vec<i32>,
  #[serde(default, skip_serializing_if = "Option::is_none")]
  pub optional_value: Option<i32>,
}

impl OptionalData {
  pub fn is_empty(&self) -> bool {
    self.optional_string.is_empty() && self.optional_array.is_empty() && self.optional_value.is_none()
  }
}

```

## Proposal

Add a trait named `IsZero` and a derive macro named `IsZero`. The above code could be simplified into:

```rust
#[derive(Default, Serialize, Deserialize)]
struct MyData {
  pub mandatory_field: i32,
  #[serde(default, skip_serializing_if = "IsZero::is_zero")]
  pub optional_data: OptionalData,
}

#[derive(Default, Serialize, Deserialize, IsZero)]
struct OptionalData {
  #[serde(default, skip_serializing_if = "IsZero::is_zero")]
  pub optional_string: String,
  #[serde(default, skip_serializing_if = "IsZero::is_zero")]
  pub optional_array: Vec<i32>,
  #[serde(default, skip_serializing_if = "IsZero::is_zero")]
  pub optional_value: Option<i32>,
}

```

Alternatively, instead of `IsZero`, we should have a trait named `Zero` that both create "zero" value and check if a value is "zero" (I am assuming that `Default` trait doesn't always return "zero").

---

<div class="post-metadata">

**Author:** ![cuviper](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/cuviper/32/1897_2.png) [@cuviper](https://internals.rust-lang.org/u/cuviper)\
**Post date:** [June 27, 2020, 3:23am UTC](https://internals.rust-lang.org/t/request-iszero-trait-and-derive-iszero/12636/2 "2020-06-27T03:23:27Z")

</div>

You could use [`num_traits::Zero`](https://docs.rs/num-traits/0.2.12/num_traits/identities/trait.Zero.html). This used to be in the standard library before Rust 1.0, but was pushed out to a crate in the final days off stabilization.

But that's only for numeric zero, not containers and such.

---

<div class="post-metadata">

**Author:** ![jhpratt](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/jhpratt/32/11640_2.png) [@jhpratt](https://internals.rust-lang.org/u/jhpratt)\
**Post date:** [June 27, 2020, 3:38am UTC](https://internals.rust-lang.org/t/request-iszero-trait-and-derive-iszero/12636/3 "2020-06-27T03:38:48Z")

</div>

Naming aside ("zero" doesn't make much sense for a string or many other data types), is there any use case for this aside from serde? Having to implement an `is_empty` method or similar doesn't seem like too big of a hurdle, imo.

---

<div class="post-metadata">

**Author:** ![KSXGitHub](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/ksxgithub/32/5582_2.png) [@KSXGitHub](https://internals.rust-lang.org/u/KSXGitHub)\
**Post date:** [June 27, 2020, 4:44am UTC](https://internals.rust-lang.org/t/request-iszero-trait-and-derive-iszero/12636/4 "2020-06-27T04:44:08Z")

</div>

> [@jhpratt](#):
>
> Having to implement an `is_empty` method or similar doesn't seem like too big of a hurdle, imo.

I would have to make N `is_empty`s for N optional structs.

---

<div class="post-metadata">

**Author:** ![CAD97](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/cad97/32/3460_2.png) [@CAD97](https://internals.rust-lang.org/u/CAD97)\
**Post date:** [June 27, 2020, 6:36am UTC](https://internals.rust-lang.org/t/request-iszero-trait-and-derive-iszero/12636/5 "2020-06-27T06:36:36Z")

</div>

Required question: can this be a userland derive macro? What benefit is there in having this in std rather than a crate? What about just the trait in std, and the derive in a crate?

Last I saw discussion around it, we might end up having a "`trait IsEmpty`" in std. We currently have an unstable `ExactSizeIterator::is_empty`, but (last I saw) general consensus was that it doesn't _really_ fit there, because an Iterator can definitively know if it's empty without knowing its exact size. Plus, things that are not iterators, just iterable, can be empty (or not). However, while none of the existing iterator traits seemed the "right" place to put `is_empty`, general temperature was that a trait for `is_empty` also felt not quite "right" either.

Personally, though, I find that this kind of aggressive "don't serialize if 'empty'" approach isn't all that great.

It's meaningful to be able to tell the difference in a configuration between "unset; use the default" and "set (to the current default)," especially if there's any chance of the default changing in the future. Additionally, `skip_serializing_if` just straight doesn't work for non-self-describing formats (such as bincode). (Thus this is for human-understandable serialization, even if not intended to be human edited.) Obviously sometimes you just have to match a JSON web payload with very weakly typed semantics (and often legacy data with the wrong shape (_cough_ trello \>.\>)), so you can't always take the "moral" path.

---

<div class="post-metadata">

**Author:** ![KSXGitHub](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/ksxgithub/32/5582_2.png) [@KSXGitHub](https://internals.rust-lang.org/u/KSXGitHub)\
**Post date:** [June 27, 2020, 7:14am UTC](https://internals.rust-lang.org/t/request-iszero-trait-and-derive-iszero/12636/6 "2020-06-27T07:14:51Z")

</div>

> [@CAD97](#):
>
> can this be a userland derive macro?

It can be.

> [@CAD97](#):
>
> What benefit is there in having this in std rather than a crate?

Convenience, widespread usage, no ecosystem split.

> [@CAD97](#):
>
> Last I saw discussion around it, we might end up having a " `trait IsEmpty` " in std. We currently have an unstable `ExactSizeIterator::is_empty` , but (last I saw) general consensus was that it doesn't _really_ fit there, because an Iterator can definitively know if it's empty without knowing its exact size. Plus, things that are not iterators, just iterable, can be empty (or not). However, while none of the existing iterator traits seemed the "right" place to put `is_empty` , general temperature was that a trait for `is_empty` also felt not quite "right" either.

My proposal is broader than just containers and iterators. It includes all numbers, things that act like numbers (such as complex numbers, vectors, matrices, etc.), anything that has an "add" operation (`n + 0 = n`, `text + "" = text`, `set + [] = set`, etc.).

---

<div class="post-metadata">

**Author:** ![canndrew](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/canndrew/32/1676_2.png) [@canndrew](https://internals.rust-lang.org/u/canndrew)\
**Post date:** [June 27, 2020, 9:27am UTC](https://internals.rust-lang.org/t/request-iszero-trait-and-derive-iszero/12636/7 "2020-06-27T09:27:12Z")

</div>

You can define this:

```rust
trait IsDefault: Default + PartialEq {
    fn is_default(&self) -> bool;
}

impl<T: Default + PartialEq> IsDefault for T {
    fn is_default(&self) -> bool {
        *self == T::default()
    }
}

```

---

<div class="post-metadata">

**Author:** ![KSXGitHub](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/ksxgithub/32/5582_2.png) [@KSXGitHub](https://internals.rust-lang.org/u/KSXGitHub)\
**Post date:** [June 27, 2020, 9:45am UTC](https://internals.rust-lang.org/t/request-iszero-trait-and-derive-iszero/12636/8 "2020-06-27T09:45:01Z")

</div>

comparison is not the most efficient operation, not to mention calling `T::default()` can be expensive.

---

<div class="post-metadata">

**Author:** ![canndrew](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/canndrew/32/1676_2.png) [@canndrew](https://internals.rust-lang.org/u/canndrew)\
**Post date:** [June 27, 2020, 10:12am UTC](https://internals.rust-lang.org/t/request-iszero-trait-and-derive-iszero/12636/9 "2020-06-27T10:12:13Z")

</div>

That's technically true, but for all the examples you've given it would be optimally efficient. eg. `Vec::default` doesn't allocate, the call would presumably get inlined, and `is_default` would reduce to a check that `len` is zero.

---

<div class="post-metadata">

**Author:** ![H2CO3](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/h2co3/32/2849_2.png) [@H2CO3](https://internals.rust-lang.org/u/H2CO3)\
**Post date:** [June 27, 2020, 10:13am UTC](https://internals.rust-lang.org/t/request-iszero-trait-and-derive-iszero/12636/10 "2020-06-27T10:13:15Z")

</div>

It _can_ be but in the overwhelming majority of cases, it isn't. Numeric types, standard collections, even things like `Box<str>` and anything that is built on these by means of `#[derive(Default)]` implement `Default` at the cost of a couple of register moves.

---

<div class="post-metadata">

**Author:** ![scottmcm](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/scottmcm/32/2355_2.png) [@scottmcm](https://internals.rust-lang.org/u/scottmcm)\
**Post date:** [June 28, 2020, 3:11am UTC](https://internals.rust-lang.org/t/request-iszero-trait-and-derive-iszero/12636/11 "2020-06-28T03:11:08Z")

</div>

Naming nit: If you want to use it on `Vec`, it shouldn't be called `IsZero`, since that could easily be confused with non-zero optimizations in enums like `Option`, where any empty `Vec` is non-zero from that perspective.

Something along the lines of "is default" may be better.

(Said without taking a position on whether the trait _should_ exist.)

---

<div class="post-metadata">

**Author:** ![kornel](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/kornel/32/2711_2.png) [@kornel](https://internals.rust-lang.org/u/kornel)\
**Post date:** [June 28, 2020, 1:13pm UTC](https://internals.rust-lang.org/t/request-iszero-trait-and-derive-iszero/12636/12 "2020-06-28T13:13:49Z")

</div>

Because it's tied to `serde(default)`, comparison with an actual `Default` value seems most correct (assuming that `Default` is deterministic, which theoretically it doesn't have to be). Otherwise it would create subtle bugs when `Default` implementation initialized values to something that isn't "zero".

Another solution could be to copy Golang's zero initialization concept, with a pair like `Zero::zero_value()` and `Zero::is_zero()`. But I'm not keen on that in Rust, since in other languages zero/falsy values are used as a less-precise `Option` alternative.

---

<div class="post-metadata">

**Author:** ![KSXGitHub](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/ksxgithub/32/5582_2.png) [@KSXGitHub](https://internals.rust-lang.org/u/KSXGitHub)\
**Post date:** [June 28, 2020, 1:47pm UTC](https://internals.rust-lang.org/t/request-iszero-trait-and-derive-iszero/12636/13 "2020-06-28T13:47:12Z")

</div>

Zero value is supposed to be a constant or a pure function.

> [@kornel](#):
>
> since in other languages zero/falsy values are used as a less-precise `Option` alternative.

You are talking about nullable types (e.g. `number | undefined` in TypeScript)? Types that `impl`s `Zero` are very different from nullable, they are just normal types (such as `i32` where "zero" is `0` or `String` where "zero" is `""`).

---

<div class="post-metadata">

**Author:** ![Ixrec](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/ixrec/32/6754_2.png) [@Ixrec](https://internals.rust-lang.org/u/Ixrec)\
**Post date:** [June 28, 2020, 1:57pm UTC](https://internals.rust-lang.org/t/request-iszero-trait-and-derive-iszero/12636/14 "2020-06-28T13:57:57Z")

</div>

> [@KSXGitHub](#):
>
> You are talking about nullable types (e.g. `number | undefined` in TypeScript)? Types that `impl` s `Zero` are very different from nullable, they are just normal types (such as `i32` where "zero" is `0` or `String` where "zero" is `""` ).

I think you misunderstood kornel since this is effectively agreeing with them despite being phrased as a disagreement.

Yes, zero values are different from nullable types. That was actually kornel's point. zero/falsy values are not a kind of nullable type, they are a "less-precise alternative" to true nullable types.

Typescript's `type | undefined` counts as true nullable types, although the benefits are a bit muddled by not having a single standard `Option`/`Maybe`/etc type like other languages with such types. Golang doesn't have nullable types in general (iiuc `nil` only applies to interface types), which I assume is because it doesn't have generics, so that's why it often ends up using a type's zero value to deal with nullability in a generic way (albeit a flawed / "less precise" way since the zero value could easily be a legitimate value as well as an absence).

---

<div class="post-metadata">

**Author:** ![jdahlstrom](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/jdahlstrom/32/3351_2.png) [@jdahlstrom](https://internals.rust-lang.org/u/jdahlstrom)\
**Post date:** [June 28, 2020, 2:54pm UTC](https://internals.rust-lang.org/t/request-iszero-trait-and-derive-iszero/12636/15 "2020-06-28T14:54:50Z")

</div>

> [@KSXGitHub](#):
>
> My proposal is broader than just containers and iterators. It includes all numbers, things that act like numbers (such as complex numbers, vectors, matrices, etc.), anything that has an "add" operation ( `n + 0 = n` , `text + "" = text` , `set + [] = set` , etc.).

For what it's worth, in formal terms such a structure is called a _[monoid](https://en.wikipedia.org/wiki/Monoid):_ a tuple ( **S** , •, 0̸) such that • is an associative binary operation over the set **S** and 0̸ ∈ **S** is the (unique) neutral element with respect to •. In other words, it is a _semigroup_ with a neutral element. In [Haskell](https://hackage.haskell.org/package/base-4.14.0.0/docs/Data-Monoid.html#t:Monoid):

```rust
class Semigroup a => Monoid a where
    mempty :: a
    mappend :: a -> a -> a

```

This is certainly a useful and very natural abstraction to have, but strictly speaking also stronger than what your `serde` use case requires.

---

<div class="post-metadata">

**Author:** ![Tom-Phinney](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/tom-phinney/32/3299_2.png) [@Tom-Phinney](https://internals.rust-lang.org/u/Tom-Phinney)\
**Post date:** [June 28, 2020, 3:53pm UTC](https://internals.rust-lang.org/t/request-iszero-trait-and-derive-iszero/12636/16 "2020-06-28T15:53:38Z")

</div>

Thank you.

My biggest problem with the OP's proposal is the use of the term "Zero" for non-numerics such as the empty string (`""`). Your note above, giving background on _monoids_, also provides a non-numeric name for the trait and derive: `IsNeutral` and `#[derive(IsNeutral)]`. I could support such names, whereas I vehemently oppose using the term "Zero" for non-numerics.

---

<div class="post-metadata">

**Author:** ![kornel](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/kornel/32/2711_2.png) [@kornel](https://internals.rust-lang.org/u/kornel)\
**Post date:** [June 28, 2020, 7:14pm UTC](https://internals.rust-lang.org/t/request-iszero-trait-and-derive-iszero/12636/17 "2020-06-28T19:14:45Z")

</div>

I mean treating an empty string as a sentinel value. `Option<String>` can tell a difference between value not being set at all, and a value intentionally set to an empty string.

That distinction may be useless in your case. But when it's built-in into the language, it becomes more widely used, and becomes something that needs to be considered when defining structs — that's my impression from Golang.

JS has `null`/`undefined` that can be set even on string fields, but in this case Rust's `IsZero` would be closer to Golang. Golang can't set `string` to `nil`, so the zero value of a `string` is an empty string.

---

<div class="post-metadata">

**Author:** ![Tom-Phinney](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/tom-phinney/32/3299_2.png) [@Tom-Phinney](https://internals.rust-lang.org/u/Tom-Phinney)\
**Post date:** [June 28, 2020, 7:58pm UTC](https://internals.rust-lang.org/t/request-iszero-trait-and-derive-iszero/12636/18 "2020-06-28T19:58:53Z")

</div>

But it's not "the zero value"; it's the additive identiy under `+` as the string concatenation operator.

---

<div class="post-metadata">

**Author:** ![eminence](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/eminence/32/4018_2.png) [@eminence](https://internals.rust-lang.org/u/eminence)\
**Post date:** [June 28, 2020, 11:48pm UTC](https://internals.rust-lang.org/t/request-iszero-trait-and-derive-iszero/12636/19 "2020-06-28T23:48:42Z")

</div>

> [@KSXGitHub](#):
>
> > [@CAD97](#):
> >
> > What benefit is there in having this in std rather than a crate?
> 
> Convenience, widespread usage, no ecosystem split.

What did you have in mind when you said "ecosystem split"? In my mind, an "ecosystem split" happens when you have two crates that do something similar, but are mutually incompatible, or prevent composition in some important way.

I don't see that happening if this feature is implemented in a crate. If both you and I implement a crate that provides an `IsZero` or `IsEmpty` trait, downstream crates would be able pick either one (or even use both) without risking any incompatibility.

---

<div class="post-metadata">

**Author:** ![KSXGitHub](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/ksxgithub/32/5582_2.png) [@KSXGitHub](https://internals.rust-lang.org/u/KSXGitHub)\
**Post date:** [June 29, 2020, 12:09am UTC](https://internals.rust-lang.org/t/request-iszero-trait-and-derive-iszero/12636/20 "2020-06-29T00:09:46Z")

</div>

> [@kornel](#):
>
> JS has `null` / `undefined` that can be set even on string fields

JavaScript does not have static typing. TypeScript has static typing, and when `"strictNullCheck"` is set to `true` (recommended practice, but sadly not default due to backward compatibility), a variable of type `string` cannot be set to `undefined` or `null`.

> [@kornel](#):
>
> but in this case Rust's `IsZero` would be closer to Golang

Go does not have `Option` or nullable so developer have to resort to use zero values. But Rust has `Option`, why would a Rust developer treat zero values as "unset".

(to clarify, in my use case, I don't treat zero value as `null` either, I merely see that explicitly setting something to zero is redundant)

[Next page](https://internals.rust-lang.org/t/request-iszero-trait-and-derive-iszero/12636.md?page=2)
