Dhghomon / rust-fsharp

Rust - F# - Rust reference
MIT License
239 stars 14 forks source link

Use of "shadowing" #3

Closed isaacabraham closed 3 years ago

isaacabraham commented 3 years ago

Maybe means something different in Rust, but in F# shadowing isn't really (at least, in my understanding) what you're referring to. In F#, shadowing refers more to symbols than types e.g.

let x = 1
let y = x + 10 // this is fine
let x = "hello" // shadows x, the other x is now out of scope
let z = x + 10 // this now won't work, x is now referring to the string "hello"
Dhghomon commented 3 years ago

Actually that's the way we do it in Rust too. Here's the exact same thing in Rust:

fn main() {
    let x = 1;
    let y = x + 10; // this is fine
    let x = "hello"; // shadows x, the other x is now out of scope
    let z = x + 10; // this now won't work, x is now referring to the string "hello"
}

Link to the playground if you want to try it out: https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=b040e30f78aec58a9ed9a5e54c3daa8f

Now one thing I'm not sure is the same (but I assume is) is if you drop x, or if x's scope ends before the original x, the original x comes back. Also, if you make a variable that references the original x, it will still reference that original x value (which makes sense).

Here's an example of that:

https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=c0a657938497e604e544b077b3664fc5

isaacabraham commented 3 years ago

Yep, that's pretty much the same as F# AFAIK.