What values are computed at runtime?

Hello,

The problem :

In the rustup doc --book in the cmd, there was this phrase that I failed to understand.

The last difference is that constants may be set only to a constant expression, not the result of a value that could only be computed at runtime.

The question :

What is runtime and why would there be an emphasis on the values computed at runtime ? Does that mean that there would be 2 kind of values, those computed at runtime and those computed outside runtime ? If so, then what would be the difference ? Why would values (if I understand values to be the entities assigned to variables) definied in a given program be computed at somewhere else than the compilation phase ? I always thought that computation happened only during the compilation phase. If the compilation phase transforms the program to a software, where else could any value from the originaly written program be computed and for what end ?

Thanks and have a good day

It is computed at the compilation phase, not the runtime phase.

1 Like

Rust is a compiled language, meaning that the compiler translates your source code into an executable binary. Then you execute the binary to run the program. Compile time is when the compiler is doing the translation of your source code. Runtime is when you execute the binary. Constants are computed by the compiler during compile time.

There's no way to compute the value of len (or the contents of buffer) in the below program until the binary is executed and the user inputs a line, which all happens after compilation.

fn main() {
    let mut buffer = String::new();
    if let Ok(_) = std::io::stdin().read_line(&mut buffer) {
        let len = buffer.len();
        println!("{len}")
    }
}
1 Like

Thanks for the answer

Thanks for the answer, now I know what's the meaning of runtime, it's the moment when the end user uses the software. And with this example, we clearly see that the value of len for example is only computed when using the program and could not be known during the compilation phase.
This was very useful. Thank you and have a good day