What are record's layout

The following question has been asked on Telegram:

i still cannot capture usage of layout :s i treat sp.record as struct of solidity, i need not to care order of struct, why i need to care that in smartpy?

Michelson (the Tezos language into which SmartPy is compiled) doesn’t have a native record type, so developers use nested pairs to mimic records. The “right comb” layout is a standardized way to organize these pairs, ensuring consistency and simplifying data access. It’s structured as a binary tree where each left child is numbered k+1 and each right child is k+2, starting from the root numbered 0.

The nodes of a right comb of size n are canonically numbered as follows:

  /   \
1       2
      /   \
    3       4
          /   \
        5       ...
                   /      \
              2n-3          2n-2

Or in plain English:

        The root is numbered 0,
        The left child of the node numbered k is numbered k+1, and
        The right child of the node numbered k is numbered k+2.

SmartPy abstracts the complexities and you should only bother when working with legacy standard or code like the FA2 standard, that don’t use right comb. In this case, simply provide the layout associated to the standard and SmartPy will compile the elements in the right order.