ahamez
Renaming a struct (or how to achieve "strong aliasing"?)
Hi all,
Let’s suppose I have the following struct:
defmodule DataType do
defstruct ~w(a b c d e f)a
end
This struct is parsed from a byte stream and represents a generic data type. However, different messages can be of this data type.
Now, I would like to achieve some kind of “strong aliasing” by having multiple structs representing these messages to share the same underlying structure. For instance:
defmodule Message1 do
defstruct ~w(a b c d e f)a
end
defmodule Message2 do
defstruct ~w(a b c d e f)a
end
Then, I want to “change” the type of DataType into Message1, Message2, etc., depending on the context in which they’ve been parsed.
I know I could use encapsulation, but it would add an indirection layer.
So far, I’ve tried this to copy the layout from DataType:
defmodule Message1 do
defstruct Map.keys(%DataType{})
end
defmodule Message2 do
defstruct Map.keys(%DataType{})
end
Then, once a DataType has been parsed, I juste rename the structure like this:
data = DataType.parse_bytes(bytes)
Map.put(data, :__struct__, Message1)
It works, but it seems a little awkward!
Can I expect some shortcomings? Is there better way to achieve this “strong” typing?
Popular in Questions
Other popular topics
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #channels
- #elixirconf
- #exunit
- #discussion
- #code-sync
- #javascript
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixir-ls
- #phoenix_html
- #iex
- #blog-post
- #graphql
- #genstage
- #ai
- #websockets
- #supervisor
- #advent-of-code
- #elixirconf-us
- #distillery
- #processes
- #forms
- #api
- #metaprogramming
- #security
- #performance








