Magnesium has a lower electrochemical potential than the steel used to build the water heater tank. This means the minerals, oxygen, and electric currents in the hot water will aggressively attack and corrode the magnesium rod instead of the steel tank lining.
Protecting the Tank: As long as the magnesium anode is present, it "sacrifices" itself by slowly dissolving over time, keeping the metal shell of the water heater completely free from rust and preventing catastrophic leaks.