[fpc-pascal] Option type

Martin Frb lazarus at mfriebe.de
Wed Jun 2 12:51:54 CEST 2021


On 01/06/2021 22:40, Sven Barth via fpc-pascal wrote:
> Am 01.06.2021 um 20:20 schrieb denisgolovan via fpc-pascal:
>>
>> I am trying to implement Option<T> type in FPC.
>>
>> type
>>    generic TOption<T> = record
>>      case IsSome:boolean of
>>      true: ( some: T );
>>      false: ();
>>    end;

Well as already discovered type like strings can not go into a "record case"

But... The above record is anyway of constant size. I.e. the memory for 
the field is always included, even if it is not used.

Since the "false" block is empty, you can do

type
    generic TOption<T> = record
      IsSome:boolean;
      some: T;
    end;

It is not as expressive to the reader of the code. But it leads to the 
same data in memory.

There is only a diff, if the other blocks of the record (the false 
block) also has/have data.
With case the memory will overlap.


More information about the fpc-pascal mailing list