| title | Comparing Data by Value with Data.struct | |||||
|---|---|---|---|---|---|---|
| id | data-struct | |||||
| skillLevel | beginner | |||||
| applicationPatternId | core-concepts | |||||
| summary | Use Data.struct to create immutable, structurally-typed objects that can be compared by value, not by reference. | |||||
| tags |
|
|||||
| rule |
|
|||||
| related |
|
|||||
| author | PaulJPhilp | |||||
| lessonOrder | 4 |
Use Data.struct to create immutable, structurally-typed objects whose equality is based on their contents, not their reference.
This enables safe, predictable comparisons and is ideal for domain modeling.
JavaScript objects are compared by reference, which can lead to subtle bugs when modeling value objects.
Data.struct ensures that two objects with the same contents are considered equal, supporting value-based logic and collections.
import { Data, Equal } from "effect";
// Create two structurally equal objects
const user1 = Data.struct({ id: 1, name: "Alice" });
const user2 = Data.struct({ id: 1, name: "Alice" });
// Compare by value, not reference
const areEqual = Equal.equals(user1, user2); // true
// Use in a HashSet or as keys in a Map
import { HashSet } from "effect";
const set = HashSet.make(user1);
console.log(HashSet.has(set, user2)); // trueExplanation:
Data.structcreates immutable objects with value-based equality.- Use for domain entities, value objects, and when storing objects in sets or as map keys.
- Avoids bugs from reference-based comparison.
Using plain JavaScript objects for value-based logic, which compares by reference and can lead to incorrect equality checks and collection behavior.