Skip to content

Native Equality Support for Structs #60

Description

@musicq

Currently, since struct instances are sealed, there is no built-in mechanism for native deep equality checks.

This limitation often requires developers to rely on helper functions like deepEqual to compare objects based on their data rather than their references.

const a1 = {name: "a", school: {grade: 1}}
const a2 = {name: "a", school: {grade: 1}}

deepEqual(a1, a2)

While this works, certain scenarios make implementing deep equality challenging. For example, in React, dependency arrays ([]) in hooks like useEffect rely on strict reference equality (===). If an object is passed directly without ensuring it retains the same reference, the behavior can become unpredictable:

const person = {name: "a"}

useEffect(() => {
  console.log(Math.random()) // // This runs unexpectedly if `person`'s reference changes
}, [person])

In cases like these, the lack of a native equality mechanism for struct instances increases cognitive overhead and complicates development.

Proposed Solution

If struct could natively support deep equality checks, it would significantly reduce the mental load for developers, particularly in scenarios where strict reference equality is not practical or desired. For example:

struct Person {
  constructor(name) { this.name = name; }
  name;
}

const a1 = new Person("a")
const a2 = new Person("a")

assert(a1 === a2)

Benefits

  • Improved Developer Experience: Reduces the need for custom deep equality functions.
  • Enhanced React Usability: Simplifies dependency tracking in hooks by ensuring consistent behavior with structured data.
  • Cleaner Code: Avoids unnecessary boilerplate or workaround patterns to achieve expected equality checks.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions