How do you check for the type of variable in Elixir

前端 未结 8 1436
走了就别回头了
走了就别回头了 2021-01-30 15:25

In Elixir how do you check for type such as in Python:

>>> a = \"test\"
>>> type(a)

>>> b =10
>>> type(b         


        
8条回答
  •  忘了有多久
    2021-01-30 15:59

    Starting in elixir 1.2 there is an i command in iex that will list the type and more of any Elixir variable.

    iex> foo = "a string" 
    iex> i foo 
    Term
     "a string"
    Data type
     BitString
    Byte size
     8
    Description
     This is a string: a UTF-8 encoded binary. It's printed surrounded by
     "double quotes" because all UTF-8 encoded codepoints in it are        printable.
    Raw representation
      <<97, 32, 115, 116, 114, 105, 110, 103>>
    Reference modules
      String, :binary
    

    If you look in the code for the i command you'll see that this is implemented via a Protocol.

    https://github.com/elixir-lang/elixir/blob/master/lib/iex/lib/iex/info.ex

    If you want to implement a function for any Data type in Elixir, the way to do that is to define a Protocol and implementation of the Protocol for all the data types you want the function to work on. Unfortunately, you can't use a Protocol function in guards. However, a simple "type" protocol would be very straightforward to implement.

提交回复
热议问题