位语法默认值

在位语法上澄清 Erlang 文档

4.4 默认值

[开头省略:<< 3.14 >>甚至不是合法的语法。]

默认大小取决于类型。对于整数,它是 8.对于 float,它是 64.对于二进制,它是指定二进制文件的实际大小:

    1> Bin = << 17/integer, 3.2/float, <<97, 98, 99>>/binary >>. 
    <<17,64,9,153,153,153,153,153,154,97,98,99>>
      ^ |<-------------------------->|<------>|
      |            float=64           binary=24
  integer=8


    2> `size(Bin)`. % Returns the number of bytes:
    12            % 8 bits + 64 bits + 3*8 bits = 96 bits => 96/8 = 12 bytes

在匹配时,只允许在模式的末尾使用没有 Size 的二进制段,默认的 Size 是匹配右侧的二进制的其余部分:

25> Bin = <<97, 98, 99>>. 
<<"abc">>

26> << X/integer, Rest/binary >> = Bin. 
<<"abc">>

27> X. 
97

28> Rest. 
<<"bc">>

模式中具有二进制类型的所有其他段必须指定大小:

12> Bin = <<97, 98, 99, 100>>.         
<<"abcd">>

13> << B:1/binary, X/integer, Rest/binary >> = Bin. %'unit' defaults to 8 for  
<<"abcd">>                    %binary type, total segment size is Size * unit  

14> B.
<<"a">>

15> X.
98

16> Rest.
<<"cd">>

17> << B2/binary, X2/integer, Rest2/binary >> = Bin. 
* 1: a binary field without size is only allowed at the end of a binary pattern