Preventing rust is no magic science. Rust is simply the oxidation of iron in the metal. For rust to happen we really only need to introduce one ingredient: oxygen (the iron is a given in steel).
Water is just an electrolyte that facilitates the bonding of oxygen atoms with iron atoms.
The way any rust preventative works, such as paint, or oil, is by creating a coating that protects the steel from oxygen and electrolytes (like water). So anything you put on your metal, including WD40, will prevent rust if it is sufficient to prevent the steel from exposure. Water by itself is a very weak electrolyte and not very efficient at causing rust. I have seen unprotected steel hold up very well under water where it is not exposed to atmospheric gases like oxygen and carbon dioxide, which facilitate the corrosion action. That's why we really don't have to worry about our gun barrels rusting while they are full of water during the cleaning process, but after they are emptied and exposed to the atmosphere.
All I know about WD40 is that is was created to displace water, not to be a lubricant. I don't know how long it lasts before it breaks down or evaporates away, leaving the metal unprotected.
Since there is always moisture present in the atmosphere, displacing or drying the ambient water from cleaning is only half the battle.
Some guys like Ballistol because it emulsifies (mixes) with water rather than displaces it. The theory then is that as the water evaporates, it leaves behind the Ballistol which serves as the protective coating. I can't speak for how long that film lasts, but I have much more confidence in a stable oil film that protects the steel from exposure than I do a product that was only ever intended to displace water. But if WD40 does leave behind a film or coating that covers the steel on a long term basis, I don't see why it wouldn't be just as effective.
I use simple food grade vegetable oil to protect my hunting knives from rust, and that seems to work very well, and that contains no magic additives or ingredients.