How to understand zero cost abstraction for Rust

For example in Python sum(range(1000)) actually does 1000 iterations and 1000 additions, so there's a cost to writing it that way.

OTOH in Rust (0..1000).sum() compiles down to the constant 499500, so it costs nothing to execute.

Similar optimizations are also possible in other compiled languages, so Rust isn't entirely unique in having zero-cost abstractions like this.

The most notable difference is that Rust can track memory using lifetimes (zero cost at runtime) instead of reference counting or GC. In C++ you either don't get the abstraction and manage moving and freeing yourself, or you pay the cost of some form of GC.