alamba78
Double Colon operator
I’m getting back into learning Elixir after a couple weeks off and for the life of me I can’t remember (or maybe never came across) what the double colon :: operator is used for.
I’m reading The Little Elixir and OTP Guidebook and there is an example in Chapter 2 using it (without an explanation or introduction to the operator). Here is the snippet of code from the example:
<< “TAG”, title :: binary-size(30),
artist :: binary-size(30),
album :: binary-size(30),
year :: binary-size(4),
_rest :: binary >> = id3_tag
Can someone explain the use of the :: operator?
Thanks!
Marked As Solved
alamba78
Wow, thanks for the link to the documentation and your explanation. Everyone that replied has really helped out and I’m sure many more people have gained an understanding of the use of :: .
Also Liked
Qqwy
The double colon (::) has two uses. Both could be subscribed as “being of type”:
- In binaries, it is used to explain what size(bit/byte/multiple bytes) an element in the binary is. An example, taken from the Parsing UDP with Binary Pattern Matching blog post:
<<
_header :: size(240), # 30 bytes * 8 = 240 bits
priority_code :: bitstring-size(8),
agent_number :: little-unsigned-integer-size(32),
message :: bitstring-size(320)
>> = data
When pattern matching with binaries, a size has to be specified for all but the last element to-be-matched element.
2.In specifying what return type a function has, when writing @spec, @type or @callback attributes:
@spec fibonacci(int) :: int
@type num_or_str :: number | string
@callback read_description(Entity.t) :: iodata
jimm
It’s not an operator. Think of it as saying “is of size” So title
is-of-size 30 bits.
gregvaughn
It looks like that is binary pattern matching, so the value after the double colon specifies the size of the value before it.
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










