How to print a variable in another function in main?

fn main() {
    
}

fn hi() {
    let x = "hi";
}

Hi

I was wondering how do I access the variable x in the hi function in main() and print it out in main without modifying anything in the hi function.

Thanks

you can't, at least not without modifying hi

Why not?

why not?

Variables in a function only exist while that function is being executed.

Ok how do I execute the high function in main and print out x without modifying the hi function.

You can't. The variable is only around while hi is being executed. main doesn't have access to it.

Why do you want to print it out?

You will either have to return the value of x from hi, or you will need to print out the value of x inside of hi. You can't do it from main. You can't inspect the local variables of functions from outside that function.

Ok how do I return the value of x from hi?

fn hi() -> &'static str {
    let x = "hi";
    x
}
1 Like

Then how do I print it out in main?

fn main() {
    let hi_x = hi();
    println!("{}", hi_x);
}

Have you read the book? It goes over all this and more. I highly reccomend reading it.

2 Likes

I which section is this stuff covered?

Printing variables
Returning values

Ok if I have more than one variable in hi function how do I return and print out the values in main?
For example:

fn hi() -> &'static str {
    let x = "hi";
    x
    let y = "bye";
    y
    let z = "no";
    z
}

Ok if I have more than one variable in hi function how do I return and print out the values in main?
For example:

fn hi() -> &'static str {
    let x = "hi";
    x
    let y = "bye";
    y
    let z = "no";
    z
}

You can use a tuple.

fn hi() -> (&'static str, &'static str, &'static str) {
    let x = "hi";
    let y = "bye";
    let z = "no";
    (x, y, z)
}

fn main() {
    let (x, y, z) = hi();
    println!("{}", x);
    println!("{}", y);
    println!("{}", z);
}

I agree with @KrishnaSannasi; I think reading through the first few chapters of the book will do a better job of explaining this kind of stuff than walking through it step by step here. I'd get through at least the chapter "Programming a Guessing Game".

I just I recently started learning Rust having programmed in Python. The stuff in Rust just feels totally different to Python and still hard for me to get used to the Rust of way of programming.

Yes, Rust is a completely different beast from Python, and is much stricter about it's rules. The book does a very good job of explaining this, more so than the two of us can do.

1 Like

So does Rust have everything that Python does?