How to get values from functions from within an if statement [duplicate] - rust

This question already has answers here:
How do I access a variable outside of an `if let` expression?
(3 answers)
Closed 3 years ago.
I am trying to avoid running a function if the user presents some information.
if let Some(app) = app.subcommand_matches("Download") {
if app.is_present("Server") {
let best = app.value_of("Server").unwrap();
} else {
let best = server::best_server("3").unwrap().to_owned();
let best = best.id.as_str();
};
let bytes = app.value_of("bytes").unwrap_or("100000024");
let dl = server::download(best, bytes).unwrap();
println!("Download Results {:#?} mbps", dl);
}
I would expect the code to only run best_server if app.is_present exists.
Why does assigning "best" inside the if statement end in the following error :
--> src/main.rs:80:35
|
80 | let dl = server::download(best.id.as_str(), bytes).unwrap();
| ^^^^ not found in this scope

When you use the let keyword you are declaring the given variable within the scope that the statement appears. The scope starts from the enclosing opening brace { and ends at the enclosing closing brace }.
So this:
if app.is_present("Server") {
let best = app.value_of("Server").unwrap();
}
declares a variable best, but that variable does not exist after the closing brace. That's why the error you are getting says the variable does not exist.
One way to fix this is to take advantage of the fact that an if statement has a value: the value of the last expression within the selected branch. So you could say:
let best = if app.is_present("Server") {
app.value_of("Server").unwrap()
} else {
server::best_server("3").unwrap().to_owned().id.as_str()
};
Note the lack of a ; on the end of the expressions within the if statement branches. If there was a semicolon there then the value of the expression would not be assigned.

Related

How can I debug some Rust code to find out why the "if" statement doesn't run? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
This code is what I made from looking at the book "Hands-on Rust", it's basically a copy of the code from the "Searching an Array" part. I don't know why the "if valid" statement doesn't run even though the variable should be set to true.
use std::io::stdin;
fn main() {
println!("Please enter the key"); //prints the string
let mut enter = String::new(); //initiates the changeable variable "enter"
stdin().read_line(&mut enter).expect(r#"invalid key"#); //allows user input and reads the input to assign into the "enter" variable
enter.trim().to_lowercase(); //trims the "enter" variable out of non-letter inputs and turns them into lowercase
let key_list = ["1", "2", "3"]; //the input needed to get the desired output
let mut valid = false; //initiates the "valid" variable to false
for key in &key_list { //runs the block of code for each item in the "key_list" array
if key == &enter { //runs the block of code if the variable "enter" matches the contents of the array "key_list"
valid = true //turns the "valid" variable into true
}
};
if valid { //it will run the block of code if the variable valid is true
println!("very nice, {}", enter) //it prints the desired output
} else { //if the if statement does not fulfill the condition, the else statement's block of code will run
println!("key is either incorrect or the code for this program sucks, your input is {}", enter) //the failure output
}
}
Please pardon the absurd number of comments if it annoyed you. I did it to try and find where the bad part is.
There's a really cool macro called dbg! I love to use. It's like println! on steroids. You can wrap it around pretty much any variable, expression, or even sub-expression and it'll print the code inside it, the value, and the source location.
Let's add it to the loop and see what's going on:
for key in &key_list {
if dbg!(key) == dbg!(&enter) {
valid = true
}
};
Here's what I see:
Please enter the key
1
[src/main.rs:10] key = "1"
[src/main.rs:10] &enter = "1\n"
[src/main.rs:10] key = "2"
[src/main.rs:10] &enter = "1\n"
[src/main.rs:10] key = "3"
[src/main.rs:10] &enter = "1\n"
Ah! enter didn't actually get trimmed. It's still got the trailing newline. Hm, why is that? Let's take a look at the trim method:
pub fn trim(&self) -> &str
It looks like it returns a new &str slice rather than modifying the input string. We know it can't change it in place because it doesn't take &mut self.
to_lowercase is the same:
pub fn to_lowercase(&self) -> String
The fix:
let enter = enter.trim().to_lowercase();
The problem is that stdin().read_line() returns the input with a trailing newline, but str.trim() and str.to_lowercase() does not mutate the original str. You have to assign it back to enter:
enter = enter.trim().to_lowercase();
You could have spotted it by printing println!("your input is {:?}", enter) with the Debug format specifier, or the other option suggested in John's answer.

Rust: What does the `#` (at sign) operator do?

I saw the following line in my code, and I am not sure what it does as I haven't encountered the # operator before.
if let e#Err(_) = changed {
...
}
Can this line be written without the # operator, what would that look like?
It's a way to bind the matched value of a pattern to a variable(using the syntax: variable # subpattern). For example,
let x = 2;
match x {
e # 1 ..= 5 => println!("got a range element {}", e),
_ => println!("anything"),
}
According to https://doc.rust-lang.org/book/ch18-03-pattern-syntax.html#-bindings and https://doc.rust-lang.org/reference/patterns.html#identifier-patterns, it is used for simultaneously matching to the pattern to the right of the # while also binding the value to the identifier to the left of the #.
To answer your second question, Yes, it would look like
if let Err(_) = &changed {
// continue to use `changed` like you would use `e`
}
Note that in order to continue to use changed inside the body, you need to match for the reference &changed. Otherwise it will be moved and discarded (unless it happens to be Copy).

Understanding Raku's `&?BLOCK` compile-time variable

I really appreciate the Raku's &?BLOCK variable – it lets you recurse within an unnamed block, which can be extremely powerful. For example, here's a simple, inline, and anonymous factorial function:
{ when $_ ≤ 1 { 1 };
$_ × &?BLOCK($_ - 1) }(5) # OUTPUT: «120»
However, I have some questions about it when used in more complex situations. Consider this code:
{ say "Part 1:";
my $a = 1;
print ' var one: '; dd $a;
print ' block one: '; dd &?BLOCK ;
{
my $a = 2;
print ' var two: '; dd $a;
print ' outer var: '; dd $OUTER::a;
print ' block two: '; dd &?BLOCK;
print "outer block: "; dd &?OUTER::BLOCK
}
say "\nPart 2:";
print ' block one: '; dd &?BLOCK;
print 'postfix for: '; dd &?BLOCK for (1);
print ' prefix for: '; for (1) { dd &?BLOCK }
};
which yields this output (I've shortened the block IDs):
Part 1:
var one: Int $a = 1
block one: -> ;; $_? is raw = OUTER::<$_> { #`(Block|…6696) ... }
var two: Int $a = 2
outer var: Int $a = 1
block two: -> ;; $_? is raw = OUTER::<$_> { #`(Block|…8496) ... }
outer block: -> ;; $_? is raw = OUTER::<$_> { #`(Block|…8496) ... }
Part 2:
block one: -> ;; $_? is raw = OUTER::<$_> { #`(Block|…6696) ... }
postfix for: -> ;; $_ is raw { #`(Block|…9000) ... }
prefix for: -> ;; $_ is raw { #`(Block|…9360) ... }
Here's what I don't understand about that: why does the &?OUTER::BLOCK refer (based on its ID) to block two rather than block one? Using OUTER with $a correctly causes it to refer to the outer scope, but the same thing doesn't work with &?BLOCK. Is it just not possible to use OUTER with &?BLOCK? If not, is there a way to access the outer block from the inner block? (I know that I can assign &?BLOCK to a named variable in the outer block and then access that variable in the inner block. I view that as a workaround but not a full solution because it sacrifices the ability to refer to unnamed blocks, which is where much of &?BLOCK's power comes from.)
Second, I am very confused by Part 2. I understand why the &?BLOCK that follows the prefix for refers to an inner block. But why does the &?BLOCK that precedes the postfix for also refer to its own block? Is a block implicitly created around the body of the for statement? My understanding is that the postfix forms were useful in large part because they do not require blocks. Is that incorrect?
Finally, why do some of the blocks have OUTER::<$_> in the but others do not? I'm especially confused by Block 2, which is not the outermost block.
Thanks in advance for any help you can offer! (And if any of the code behavior shown above indicates a Rakudo bug, I am happy to write it up as an issue.)
That's some pretty confusing stuff you've encountered. That said, it does all make some kind of sense...
Why does the &?OUTER::BLOCK refer (based on its ID) to block two rather than block one?
Per the doc, &?BLOCK is a "special compile variable", as is the case for all variables that have a ? as their twigil.
As such it's not a symbol that can be looked up at run-time, which is what syntax like $FOO::bar is supposed to be about afaik.
So I think the compiler ought by rights reject use of a "compile variable" with the package lookup syntax. (Though I'm not sure. Does it make sense to do "run-time" lookups in the COMPILING package?)
There may already be a bug filed (in either of the GH repos rakudo/rakudo/issues or raku/old-issues-tracker/issues) about it being erroneous to try to do a run-time lookup of a special compile variable (the ones with a ? twigil). If not, it makes sense to me to file one.
Using OUTER with $a correctly causes it to refer to the outer scope
The symbol associated with the $a variable in the outer block is stored in the stash associated with the outer block. This is what's referenced by OUTER.
Is it just not possible to use OUTER with &?BLOCK?
I reckon not for the reasons given above. Let's see if anyone corrects me.
If not, is there a way to access the outer block from the inner block?
You could pass it as an argument. In other words, close the inner block with }(&?BLOCK); instead of just }. Then you'd have it available as $_ in the inner block.
Why does the &?BLOCK that precedes the postfix for also refer to its own block?
It is surprising until you know why, but...
Is a block implicitly created around the body of the for statement?
Seems so, so the body can take an argument passed by each iteration of the for.
My understanding is that the postfix forms were useful in large part because they do not require blocks.
I've always thought of their benefit as being that they A) avoid a separate lexical scope and B) avoid having to type in the braces.
Is that incorrect?
It seems so. for has to be able to supply a distinct $_ to its statement(s) (you can put a series of statements in parens), so if you don't explicitly write braces, it still has to create a distinct lexical frame, and presumably it was considered better that the &?BLOCK variable tracked that distinct frame with its own $_, and "pretended" that was a "block", and displayed its gist with a {...}, despite there being no explicit {...}.
Why do some of the blocks have OUTER::<$_> in them but others do not?
While for (and given etc) always passes an "it" aka $_ argument to its blocks/statements, other blocks do not have an argument automatically passed to them, but they will accept one if it's manually passed by the writer of code manually passing one.
To support this wonderful idiom in which one can either pass or not pass an argument, blocks other than ones that are automatically fed an $_ are given this default of binding $_ to the outer block's $_.
I'm especially confused by Block 2, which is not the outermost block.
I'm confused by you being especially confused by that. :) If the foregoing hasn't sufficiently cleared this last aspect up for you, please comment on what it is about this last bit that's especially confusing.
During compilation the compiler has to keep track of various things. One of which is the current block that it is compiling.
The block object gets stored in the compiled code wherever it sees the special variable $?BLOCK.
Basically the compile-time variables aren't really variables, but more of a macro.
So whenever it sees $?BLOCK the compiler replaces it with whatever the current block the compiler is currently compiling.
It just happens that $?OUTER::BLOCK is somehow close enough to $?BLOCK that it replaces that too.
I can show you that there really isn't a variable by that name by trying to look it up by name.
{ say ::('&?BLOCK') } # ERROR: No such symbol '&?BLOCK'
Also every pair of {} (that isn't a hash ref or hash index) denotes a new block.
So each of these lines will say something different:
{
say $?BLOCK.WHICH;
say "{ $?BLOCK.WHICH }";
if True { say $?BLOCK.WHICH }
}
That means if you declare a variable inside one of those constructs it is contained to that construct.
"{ my $a = "abc"; say $a }"; # abc
say $a; # COMPILE ERROR: Variable '$a' is not declared
if True { my $b = "def"; say $b } # def
say $b; # COMPILE ERROR: Variable '$b' is not declared
In the case of postfix for, the left side needs to be a lambda/closure so that for can set $_ to the current value.
It was probably just easier to fake it up to be a Block than to create a new Code type just for that use.
Especially since an entire Raku source file is also considered a Block.
A bare Block can have an optional argument.
my &foo;
given 5 {
&foo = { say $_ }
}
foo( ); # 5
foo(42); # 42
If you give it an argument it sets $_ to that value.
If you don't, $_ will point to whatever $_ was outside of that declaration. (Closure)
For many of the uses of that construct, doing that can be very handy.
sub call-it-a (&c){
c()
}
sub call-it-b (&c, $arg){
c( $arg * 10 )
}
for ^5 {
call-it-a( { say $_ } ); # 0␤ 1␤ 2␤ 3␤ 4␤
call-it-b( { say $_ }, $_ ); # 0␤10␤20␤30␤40␤
}
For call-it-a we needed it to be a closure over $_ to work.
For call-it-b we needed it to be an argument instead.
By having :( ;; $_? is raw = OUTER::<$_> ) as the signature it caters to both use-cases.
This makes it easy to create simple lambdas that just do what you want them to do.

What is the idiomatic Rust way to deal with a lot of if-let-else code? [duplicate]

This question already has answers here:
How can I reduce the verbosity of matching every call that returns a Result or Option?
(1 answer)
How to cleanly get the path to the bash history?
(1 answer)
Closed 5 years ago.
I am trying to find out the current home directory of the user (toy project, learning Rust) and this is the code I am at currently:
let mut home_dir = if let Some(path) = env::home_dir() {
if let Some(path_str) = path.to_str() {
path_str.to_owned()
} else {
panic!("Found a home directory, but the encoding of the filename was invalid")
}
} else {
panic!("Could not find home directory for current user, specify prefix manually");
};
I come from a heavily managed-language background so maybe that is why this appears to me as a bit of an anti-pattern, but I am trying to understand if I there is a better way to do this.
In Kotlin I would deal with this situation using:
val homeDir = env.getHomeDir()?.toString() ?: throw RuntimeException(...)
The way the ? macro works in Rust requires me to use a function that returns a Result which I believe main() does not, and it doesn't necessarily make sense anyways. Any pointers?

What is the scope of let when used without in?

In a Haskell tutorial I ran across the following code:
do [...]
let atom = [first] ++ rest
return $ case atom of
Note that the let expression does not have an in block. What is the scope of such a let expression? The next line?
Simply put, it's scoped "from where it's written until the end of the do".
Note that within a do statement, let is handled differently.
According to http://www.haskell.org/haskellwiki/Monads_as_computation#Do_notation , it is interpreted as follows:
do { let <decls> ; <stmts> }
= let <decls> in do { <stmts> }
The scope is the rest of the do block.
See §3.14 of the Haskell Report (specifically, the fourth case in the translation block). (Yes, this is the section about do blocks, because let without in is only valid inside a do block, as Porges points out.)

Resources