In this paper, we study the rank distributions of linear codes. We give the analogous to the MacWilliams identity for the rank distributions of codes. The considerations of our proof can be adapted to give an alternate derivation of the identity for the Hamming metric. This derivation does not rely on the identity for the complete weight enumerator. Using the result for the rank metric, we determine the binomial moments of the rank distribution of a linear code. As an illustration of our results, we are able to give an alternate derivation of the rank distribution of maximum rank distance codes.