Diazonium salts are an important entry to aromatic hydrocarbons bearing a great variety of organic functions.
Nitrite anion is basic enough to react twice with a mineral acid like hydrochloric acid. The double protonation allows the elimination of a water molecule rendering the nitrosyl cation, strongly nucleophilic and extremely reactive. This cation is formed in situ, i.e., in the presence of the aniline.
Anilines' nitrogen, very nucleophilic, can easily react with the nitrosyl cation. This reaction leads to a cascade of intermediates which finally produce the diazonium salt.
In a first step, the amine lone electron pair bonds to the nitrosyl cation's electron defficient center which is the nitrogen. A proton is lost rendering a N-nitrosoamine, hazardous product due to its carcinogenic properties.
The N-nitrosoamine bears numerous lone electron pairs being thus basic. Do not forget that the nitrosyl cation was formed "in situ" with a strong acid. This medium is able to protonate the final N-nitrosoamine that ends up losing a water molecule.
The loss of water leads to the diazonium salt, that must be carefully stored because it tends to lose nitrogen explosively with ease. However, if the loss of nitrogen is controlled, the N2 group can be replaced by almost any other organic function (see above).