How should const be used?

I am confused as to why my code can run successfully, whereas when I asked ChatGPT, it shouldn't work. I realize that variables in Rust must be declared first, but what is this? What does 'the book' mean:

Constants are valid for the entire time a program runs, within the scope in which they were declared.

fn main(){

    println!("{}", TIGA_MENIT_DALAM_DETIK);
    const TIGA_MENIT_DALAM_DETIK: u32 = 60 * 3;

    // println!("{}", x);
    // let x = 20;
    
}

Here is output:
image

CGPT suggestion:

fn main(){
    // Declare the constant first
    const TIGA_MENIT_DALAM_DETIK: u32 = 60 * 3;

    // Now you can use it
    println!("{}", TIGA_MENIT_DALAM_DETIK);
}

Thank you for your help

Basically the same reason as why both of these work.

fn main() {
    declared_later();
    declared_later_inside_fn_item();

    fn declared_later_inside_fn_item() {}
}

fn declared_later() {}

The declaration of top level items like fns and consts are generally visible within the entire scope.

The exception is macros-by-example.


Don't be surprised with Chat GPT gets things wrong. It's not an oracle.

6 Likes

I got it, thank you. I must go to documentation, later if found something like this. Rust docs for some syntax is good enough i think.

ChatGPT uses Rust version 1.7x, does this affect its knowledge about const?

It's not really tied to any specific version. LLMs hallucinate.

8 Likes

Okay :+1: