Bear with me, this was High School chemistry - some of it is a little fuzzy.
The key is (IIRC) the Electromotive Series of metals. At the top are the active metals: potassium, phosphorus, and one other I don’t recall (Calcium?). These react on contact with air or water. Then below them are the “regular” metals:
Magnesium
Aluminum
Zinc
Iron
Tin
Lead
Finally are the “noble” or “Coinage” metals, which are relatively impervious: copper, silver, gold, platinum.
The middle series are the ones of interest here. Any metal that is higher in the list will sacrifice itself to protect any metal lower in the list from corrosion. This is called a “sacrificial anode”. If, for example, an aluminum plate and an iron plate are immersed in salt water (an “electrolyte”), the aluminum will “sacrifice” itself, (i.e. corrode) to protect the iron.
This is why the old “tin cans” didn’t work very well; tin was plated over an iron (steel) surface, because tin was relatively nonreactive. But if the tin plating was scratched, the iron would start to corrode to protect the tin, which was lower on the list of metal reactivity. Some smart cookie figured out what was happening, and substituted zinc for tin. Presto! “Galvanized” steel that is resistant to rust.
Galvanic protection can also be “forced” by using a battery to make an anode that will corrode to protect the cathode. This is called “cathodic protection”. It works even if the anode and cathode are the same metal. But using dissimilar metals achieves the same result without the need for a battery - the metals themselves are actually the battery.
To get back to the original question, magnesium might work, but it has a tendancy to form a reactive film over itself in the presence of oxygen. Aluminum or Zinc would probably work better, and be cheaper as well.
Interestingly, I worked one summer in the navy dockyard when I was a student, and heard about problems with corrosion that I would have thought was obvious to anyone with this knowledge - and the Navy should have lots of experience dealing with salt-water corrosion. It seems that the aluminum ladders that ran from the conning tower down into the submarine hull had to be replaced regularly, because they rapidly crumbled away! Well, DUH! “Put in steel ladders”, I said. “No, steel rusts and aluminum doesn’t” was the reply. As far as I know, they’re still replacing the aluminum ladders after every trip.