[ruby-core:123402] [Ruby Feature#16769] Struct.new(..., immutable: true)

Issue #16769 has been updated by CoderMiguel (Michael Newman). Breadcrumbs for those who land here early in their search: The [Data object](https://docs.ruby-lang.org/en/3.2/Data.html) is a reasonable alternative to this feature. ---------------------------------------- Feature #16769: Struct.new(..., immutable: true) https://bugs.ruby-lang.org/issues/16769#change-114771 * Author: k0kubun (Takashi Kokubun) * Status: Rejected ---------------------------------------- ## Background We've discussed interface to pass Struct attributes (like `immutable: true`, which is actually not added yet) at once. But I believe just adding `immutable: true` alone is really helpful in various cases. Thus I've spun out this ticket only for `immutable: true` from [Feature #16122]. ## Proposal ```rb Post = Struct.new(:id, :name, immutable: true) post = Post.new(1, "hello world") post.id = 2 # NoMethodError (undefined method `id=' for #<struct Post id=1, name="hello world">) ``` Given `immutable: true`, an instance returned by `.new` is frozen, and writer methods are not defined. ## Use case * Allow using Struct's nice features when we need an immutable model, instead of defining a normal class with `attr_reader`s and methods to support the Struct's features. * If it were a Struct, `to_s`, `inspect`, `==`, and a bunch of other methods are nicely defined by default. Deconstructing a Struct on Pattern Matching is also available. * This level of support from the entire ecosystem may not be available if it's just a third-party library. * We could achieve a similar thing if we call `Post.new(...).freeze` or override `#initialize` to call `freeze` inside it, but it is not fun and feels like a workaround. * Today I suggested to use Struct for a model class to take advantage of the above benefits in a code review, but the implementation stuck with a bare class with `attr_reader`s because the author didn't want writer methods to be defined (of course we don't want to manually undef them from a Struct class either) and calling `freeze` to workaround it seems tricky. I strongly desired Ruby's Struct is useful enough to cover this use case. -- https://bugs.ruby-lang.org/
participants (1)
-
CoderMiguel (Michael Newman)