mmport80
Type Checking Structs
Structs’ success typing is the same as common garden maps to Dialyzer, right?
What are the preferred ways to enforce a particular struct?
Marked As Solved
michalmuskala
Erlang 19 introduces more advanced support from dialyzer for maps -
checking specific keys and general key types. Support for those new
features is in Elixir 1.3 as well. Here’s the PR that introduced them:
https://github.com/elixir-lang/elixir/pull/4662
Also Liked
easco
In Elixir you can pattern match on the struct’s type so for example:
defmodule StructTest do
defstruct name: "Foo!"
end
defmodule TestStruct do
def takesStruct(struct = %StructTest{}) do
IO.puts(inspect struct)
end
end
The takesStruct function will only match for instances of the %StructTest{} structure.
crabonature
def takesStruct(%StructTest{} = struct) do, means:
- this function will be invoked only when you pass to it one argument which is
%StructTest{}struct, otherwise it will not be invoked - when you invoke it with proper struct, this struct will be bound to
structvariable, which you can use later in the function body.
Qqwy
You can see more information at the Typespecs page in the Documentation.
To match a Struct inside a typespec, use the normal %StructName{} syntax.
EDIT: The documentation moved to a new location.
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
- #elixirconf-us
- #advent-of-code
- #distillery
- #processes
- #forms
- #api
- #metaprogramming
- #security
- #hex









