Structs are extensions built on top of maps that provide compile-time checks and default values.
Defining structs
To define a struct, the defstruct construct is used:defmodule User do defstruct name: "John", age: 27 endThe keyword list used with defstruct defines what fields the struct will have along with their default values. Structs take the name of the module they’re defined in. In the example above, we defined a struct named User. We can now create User structs by using a syntax similar to the one used to create maps:
new_john = %User{}) ayush = %User{name: "Ayush", age: 20} megan = %User{name: "Megan"})The above code will generate three different structs with values:
%User{age: 27, name: "John"} %User{age: 20, name: "Ayush"} %User{age: 27, name: "Megan"}Structs provide compile-time guarantees that only the fields (and all of them) defined through defstruct will be allowed to exist in a struct. So you can not define your own fields once you have created the struct in the module.
Accessing and updating structs
When we discussed maps, we showed how we can access and update the fields of a map. The same techniques (and the same syntax) apply to structs as well. For example if we want to update the user we created in the earlier example, then:defmodule User do defstruct name: "John", age: 27 end john = %User{} #john right now is: %User{age: 27, name: "John"} #To access name and age of John, IO.puts(john.name) IO.puts(john.age)When running above program, it produces following result:
John 27To update a value in a struct, we'll againg use the same way we used for map,
meg = %{john | name: "Meg"}Structs can also be used in pattern matching, both for matching on the value of specific keys as well as for ensuring that the matching value is a struct of the same type as the matched value.
No comments:
Post a Comment