Scope of 'let' with shadowing and String -> &str conversionReturn local String as a slice (&str)Conversion from Option<&str> to Option<String>Unable to coerce &String to &str&str String and lifetimeReturn local String as a slice (&str)Converting from Option<String> to Option<&str>E0308 mismatched types with simple generic functionConvert Vec<String> to Vec<&str>Mismatched types error when inserting into a HashMap<&str, u64>Auto coerce &String to &strGetting mismatched types when compiling after STDIN and then math on input

Applicability of Single Responsibility Principle

How does a character multiclassing into warlock get a focus?

What is the intuitive meaning of having a linear relationship between the logs of two variables?

Is it correct to write "is not focus on"?

Greatest common substring

Lay out the Carpet

Go Pregnant or Go Home

Student evaluations of teaching assistants

If you attempt to grapple an opponent that you are hidden from, do they roll at disadvantage?

Can criminal fraud exist without damages?

when is out of tune ok?

Cynical novel that describes an America ruled by the media, arms manufacturers, and ethnic figureheads

Will it be accepted, if there is no ''Main Character" stereotype?

Can somebody explain Brexit in a few child-proof sentences?

Where in the Bible does the greeting ("Dominus Vobiscum") used at Mass come from?

Why Were Madagascar and New Zealand Discovered So Late?

Failed to fetch jessie backports repository

Can I Retrieve Email Addresses from BCC?

What are the ramifications of creating a homebrew world without an Astral Plane?

Mapping a list into a phase plot

What defines a dissertation?

How to verify if g is a generator for p?

How do I keep an essay about "feeling flat" from feeling flat?

Why does John Bercow say “unlock” after reading out the results of a vote?



Scope of 'let' with shadowing and String -> &str conversion


Return local String as a slice (&str)Conversion from Option<&str> to Option<String>Unable to coerce &String to &str&str String and lifetimeReturn local String as a slice (&str)Converting from Option<String> to Option<&str>E0308 mismatched types with simple generic functionConvert Vec<String> to Vec<&str>Mismatched types error when inserting into a HashMap<&str, u64>Auto coerce &String to &strGetting mismatched types when compiling after STDIN and then math on input













0















With the following code, I tried to return &str of temperature of user input, but in vain. Then, I am trying to return f32, but still struggle...



Q1. The reason I am getting the error at the bottom is because the scope of 'let temp = String::new();' still persists, even I 'shadow' it later by 'let temp = temp.trim().parse::<f32>();' within the loop?



Q2. How can I rewrite the code so that it returns &str?



fn gettemp() -> f32 
let temp = String::new();

loop
println!("What is your temperature?");

io::stdin().read_line(&mut temp).expect("Failed to read the line");

let temp = temp.trim().parse::<f32>();

if !temp.is_ok()
println!("Not a number!");
else
break;



temp



Error:



error[E0308]: mismatched types
--> src/main.rs:70:5
|
49 | fn gettemp() -> f32 {
| --- expected `f32` because of return type
...
70 | temp
| ^^^^ expected f32, found struct `std::string::String`
|
= note: expected type `f32`
found type `std::string::String`









share|improve this question



















  • 1





    The second question is answered here. You might want to stick to the first one.

    – E_net4
    Mar 7 at 11:58















0















With the following code, I tried to return &str of temperature of user input, but in vain. Then, I am trying to return f32, but still struggle...



Q1. The reason I am getting the error at the bottom is because the scope of 'let temp = String::new();' still persists, even I 'shadow' it later by 'let temp = temp.trim().parse::<f32>();' within the loop?



Q2. How can I rewrite the code so that it returns &str?



fn gettemp() -> f32 
let temp = String::new();

loop
println!("What is your temperature?");

io::stdin().read_line(&mut temp).expect("Failed to read the line");

let temp = temp.trim().parse::<f32>();

if !temp.is_ok()
println!("Not a number!");
else
break;



temp



Error:



error[E0308]: mismatched types
--> src/main.rs:70:5
|
49 | fn gettemp() -> f32 {
| --- expected `f32` because of return type
...
70 | temp
| ^^^^ expected f32, found struct `std::string::String`
|
= note: expected type `f32`
found type `std::string::String`









share|improve this question



















  • 1





    The second question is answered here. You might want to stick to the first one.

    – E_net4
    Mar 7 at 11:58













0












0








0








With the following code, I tried to return &str of temperature of user input, but in vain. Then, I am trying to return f32, but still struggle...



Q1. The reason I am getting the error at the bottom is because the scope of 'let temp = String::new();' still persists, even I 'shadow' it later by 'let temp = temp.trim().parse::<f32>();' within the loop?



Q2. How can I rewrite the code so that it returns &str?



fn gettemp() -> f32 
let temp = String::new();

loop
println!("What is your temperature?");

io::stdin().read_line(&mut temp).expect("Failed to read the line");

let temp = temp.trim().parse::<f32>();

if !temp.is_ok()
println!("Not a number!");
else
break;



temp



Error:



error[E0308]: mismatched types
--> src/main.rs:70:5
|
49 | fn gettemp() -> f32 {
| --- expected `f32` because of return type
...
70 | temp
| ^^^^ expected f32, found struct `std::string::String`
|
= note: expected type `f32`
found type `std::string::String`









share|improve this question
















With the following code, I tried to return &str of temperature of user input, but in vain. Then, I am trying to return f32, but still struggle...



Q1. The reason I am getting the error at the bottom is because the scope of 'let temp = String::new();' still persists, even I 'shadow' it later by 'let temp = temp.trim().parse::<f32>();' within the loop?



Q2. How can I rewrite the code so that it returns &str?



fn gettemp() -> f32 
let temp = String::new();

loop
println!("What is your temperature?");

io::stdin().read_line(&mut temp).expect("Failed to read the line");

let temp = temp.trim().parse::<f32>();

if !temp.is_ok()
println!("Not a number!");
else
break;



temp



Error:



error[E0308]: mismatched types
--> src/main.rs:70:5
|
49 | fn gettemp() -> f32 {
| --- expected `f32` because of return type
...
70 | temp
| ^^^^ expected f32, found struct `std::string::String`
|
= note: expected type `f32`
found type `std::string::String`






rust






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 7 at 22:11









A-312

7,12942855




7,12942855










asked Mar 7 at 11:45









Julia OJulia O

455




455







  • 1





    The second question is answered here. You might want to stick to the first one.

    – E_net4
    Mar 7 at 11:58












  • 1





    The second question is answered here. You might want to stick to the first one.

    – E_net4
    Mar 7 at 11:58







1




1





The second question is answered here. You might want to stick to the first one.

– E_net4
Mar 7 at 11:58





The second question is answered here. You might want to stick to the first one.

– E_net4
Mar 7 at 11:58












3 Answers
3






active

oldest

votes


















1














A1 - nope, that's not how shadowing works. Let's look at your code with comments.



fn gettemp() -> f32 
let temp = String::new(); // Outer

loop

// Here temp refers to outer one (String)
temp




A2 - you can't return &str. @E_net4 posted a link to the answer why. However, you can return String. You can do something like this nn case you'd like to have a validated String:



fn gettemp() -> String 
loop
println!("What is your temperature?");

let mut temp = String::new();
io::stdin()
.read_line(&mut temp)
.expect("Failed to read the line");

let trimmed = temp.trim();

match trimmed.parse::<f32>()
Ok(_) => return trimmed.to_string(),
Err(_) => println!("Not a number!"),
;





I see couple of another problems in your code.



let temp = String::new();


Should be let mut temp, because you'd like to borrow mutable reference later (&mut temp in the read_line call).



Another issue is the loop & read_line. read_line appends to the String. Run this code ...



let mut temp = "foo".to_string();
io::stdin().read_line(&mut temp).unwrap();
println!("-><-", temp);


... and enter 10 for example. You'll see following output ...



->foo10
<-


... which is not what you want. I'd rewrite gettemp() in this way:



fn gettemp() -> f32 
loop
println!("What is your temperature?");

let mut temp = String::new();
io::stdin()
.read_line(&mut temp)
.expect("Failed to read the line");

match temp.trim().parse()
Ok(temp) => return temp,
Err(_) => println!("Not a number!"),
;




IMHO explicit return temp is much cleaner & readable (compared to suggested break out of the loop with a value).




A3 - Why we don't need to explicitly state <f32> in temp.trim().parse()



It's inferred by the compiler.



fn gettemp() -> f32 // 1. f32 is return type
loop
println!("What is your temperature?");

let mut temp = String::new();
io::stdin()
.read_line(&mut temp)
.expect("Failed to read the line");

match temp.trim().parse() ;







share|improve this answer

























  • My question is why we don't need to explicitly state <f32> in 'temp.trim().parse()' I looked at documentation that states "Parses this string slice into another type." Can you elaborate on this, please?

    – Julia O
    Mar 10 at 4:22











  • @JuliaO I updated my answer. Check the A3 - Why we don't need to explicitly state <f32> in temp.trim().parse() at the end.

    – zrzka
    Mar 10 at 9:23


















1














Regarding question 1, you can break out of the loop with a value:



fn gettemp() -> f32 
let mut temp = String::new();

loop
println!("What is your temperature?");

io::stdin().read_line(&mut temp).expect("Failed to read the line");

let temp = temp.trim().parse::<f32>();

if !temp.is_ok()
println!("Not a number!");
else
break temp.unwrap() // yield value when breaking out of loop





This way, the whole loop's value is the thing you passed along with break.



Regarding question 2, I am not sure if you really want to do this, because &str is a borrowed type. I think you want to return an String in this case which owns the data.






share|improve this answer























  • Thanks for your comment @phimuemue. What is the difference between 'return' and 'break' with return value? Either makes any difference?

    – Julia O
    Mar 10 at 3:12











  • @JuliaO return returns from the whole function, while break prematurely exits a loop.

    – phimuemue
    Mar 10 at 13:43


















0














In your program, loop ... creates a new scope. The scope of the second temp starts where it's defined and ends when loop ends. See the following example:



fn main() 
let a = 1;

let a = 2;
println!("", a);

println!("", a);



This prints 2, 1。



If you want to return a string, use (the code is fixed according to the comment below):



fn gettemp() -> String 
loop
let mut temp = String::new();
println!("What is your temperature?");
std::io::stdin().read_line(&mut temp).expect("Failed to read the line");
temp = temp.trim().to_string();
match temp.parse::<f32>()
Err(_) => println!("Not a number!"),
_ => return temp,





&str is a borrowed reference. You cannot return a borrowed reference to a local variable which will be released when the function returns.






share|improve this answer

























  • It's wrong, see my answer. First - read_line appends to the temp - try to enter a<enter>10<enter>. temp will contain an10n and this loop will never end. Second - you're matching temp.trim().parse::<f32>() result and then you're returing untrimmed temp - try to enter 10<enter> and the return value will be "10n", not "10", which isn't probably what you want.

    – zrzka
    Mar 8 at 9:00











  • @zrzka you're right. I didn't realize read_line appends to the buffer.

    – Hong Jiang
    Mar 8 at 10:27










Your Answer






StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");

StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);

else
createEditor();

);

function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);



);













draft saved

draft discarded


















StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55043020%2fscope-of-let-with-shadowing-and-string-str-conversion%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown

























3 Answers
3






active

oldest

votes








3 Answers
3






active

oldest

votes









active

oldest

votes






active

oldest

votes









1














A1 - nope, that's not how shadowing works. Let's look at your code with comments.



fn gettemp() -> f32 
let temp = String::new(); // Outer

loop

// Here temp refers to outer one (String)
temp




A2 - you can't return &str. @E_net4 posted a link to the answer why. However, you can return String. You can do something like this nn case you'd like to have a validated String:



fn gettemp() -> String 
loop
println!("What is your temperature?");

let mut temp = String::new();
io::stdin()
.read_line(&mut temp)
.expect("Failed to read the line");

let trimmed = temp.trim();

match trimmed.parse::<f32>()
Ok(_) => return trimmed.to_string(),
Err(_) => println!("Not a number!"),
;





I see couple of another problems in your code.



let temp = String::new();


Should be let mut temp, because you'd like to borrow mutable reference later (&mut temp in the read_line call).



Another issue is the loop & read_line. read_line appends to the String. Run this code ...



let mut temp = "foo".to_string();
io::stdin().read_line(&mut temp).unwrap();
println!("-><-", temp);


... and enter 10 for example. You'll see following output ...



->foo10
<-


... which is not what you want. I'd rewrite gettemp() in this way:



fn gettemp() -> f32 
loop
println!("What is your temperature?");

let mut temp = String::new();
io::stdin()
.read_line(&mut temp)
.expect("Failed to read the line");

match temp.trim().parse()
Ok(temp) => return temp,
Err(_) => println!("Not a number!"),
;




IMHO explicit return temp is much cleaner & readable (compared to suggested break out of the loop with a value).




A3 - Why we don't need to explicitly state <f32> in temp.trim().parse()



It's inferred by the compiler.



fn gettemp() -> f32 // 1. f32 is return type
loop
println!("What is your temperature?");

let mut temp = String::new();
io::stdin()
.read_line(&mut temp)
.expect("Failed to read the line");

match temp.trim().parse() ;







share|improve this answer

























  • My question is why we don't need to explicitly state <f32> in 'temp.trim().parse()' I looked at documentation that states "Parses this string slice into another type." Can you elaborate on this, please?

    – Julia O
    Mar 10 at 4:22











  • @JuliaO I updated my answer. Check the A3 - Why we don't need to explicitly state <f32> in temp.trim().parse() at the end.

    – zrzka
    Mar 10 at 9:23















1














A1 - nope, that's not how shadowing works. Let's look at your code with comments.



fn gettemp() -> f32 
let temp = String::new(); // Outer

loop

// Here temp refers to outer one (String)
temp




A2 - you can't return &str. @E_net4 posted a link to the answer why. However, you can return String. You can do something like this nn case you'd like to have a validated String:



fn gettemp() -> String 
loop
println!("What is your temperature?");

let mut temp = String::new();
io::stdin()
.read_line(&mut temp)
.expect("Failed to read the line");

let trimmed = temp.trim();

match trimmed.parse::<f32>()
Ok(_) => return trimmed.to_string(),
Err(_) => println!("Not a number!"),
;





I see couple of another problems in your code.



let temp = String::new();


Should be let mut temp, because you'd like to borrow mutable reference later (&mut temp in the read_line call).



Another issue is the loop & read_line. read_line appends to the String. Run this code ...



let mut temp = "foo".to_string();
io::stdin().read_line(&mut temp).unwrap();
println!("-><-", temp);


... and enter 10 for example. You'll see following output ...



->foo10
<-


... which is not what you want. I'd rewrite gettemp() in this way:



fn gettemp() -> f32 
loop
println!("What is your temperature?");

let mut temp = String::new();
io::stdin()
.read_line(&mut temp)
.expect("Failed to read the line");

match temp.trim().parse()
Ok(temp) => return temp,
Err(_) => println!("Not a number!"),
;




IMHO explicit return temp is much cleaner & readable (compared to suggested break out of the loop with a value).




A3 - Why we don't need to explicitly state <f32> in temp.trim().parse()



It's inferred by the compiler.



fn gettemp() -> f32 // 1. f32 is return type
loop
println!("What is your temperature?");

let mut temp = String::new();
io::stdin()
.read_line(&mut temp)
.expect("Failed to read the line");

match temp.trim().parse() ;







share|improve this answer

























  • My question is why we don't need to explicitly state <f32> in 'temp.trim().parse()' I looked at documentation that states "Parses this string slice into another type." Can you elaborate on this, please?

    – Julia O
    Mar 10 at 4:22











  • @JuliaO I updated my answer. Check the A3 - Why we don't need to explicitly state <f32> in temp.trim().parse() at the end.

    – zrzka
    Mar 10 at 9:23













1












1








1







A1 - nope, that's not how shadowing works. Let's look at your code with comments.



fn gettemp() -> f32 
let temp = String::new(); // Outer

loop

// Here temp refers to outer one (String)
temp




A2 - you can't return &str. @E_net4 posted a link to the answer why. However, you can return String. You can do something like this nn case you'd like to have a validated String:



fn gettemp() -> String 
loop
println!("What is your temperature?");

let mut temp = String::new();
io::stdin()
.read_line(&mut temp)
.expect("Failed to read the line");

let trimmed = temp.trim();

match trimmed.parse::<f32>()
Ok(_) => return trimmed.to_string(),
Err(_) => println!("Not a number!"),
;





I see couple of another problems in your code.



let temp = String::new();


Should be let mut temp, because you'd like to borrow mutable reference later (&mut temp in the read_line call).



Another issue is the loop & read_line. read_line appends to the String. Run this code ...



let mut temp = "foo".to_string();
io::stdin().read_line(&mut temp).unwrap();
println!("-><-", temp);


... and enter 10 for example. You'll see following output ...



->foo10
<-


... which is not what you want. I'd rewrite gettemp() in this way:



fn gettemp() -> f32 
loop
println!("What is your temperature?");

let mut temp = String::new();
io::stdin()
.read_line(&mut temp)
.expect("Failed to read the line");

match temp.trim().parse()
Ok(temp) => return temp,
Err(_) => println!("Not a number!"),
;




IMHO explicit return temp is much cleaner & readable (compared to suggested break out of the loop with a value).




A3 - Why we don't need to explicitly state <f32> in temp.trim().parse()



It's inferred by the compiler.



fn gettemp() -> f32 // 1. f32 is return type
loop
println!("What is your temperature?");

let mut temp = String::new();
io::stdin()
.read_line(&mut temp)
.expect("Failed to read the line");

match temp.trim().parse() ;







share|improve this answer















A1 - nope, that's not how shadowing works. Let's look at your code with comments.



fn gettemp() -> f32 
let temp = String::new(); // Outer

loop

// Here temp refers to outer one (String)
temp




A2 - you can't return &str. @E_net4 posted a link to the answer why. However, you can return String. You can do something like this nn case you'd like to have a validated String:



fn gettemp() -> String 
loop
println!("What is your temperature?");

let mut temp = String::new();
io::stdin()
.read_line(&mut temp)
.expect("Failed to read the line");

let trimmed = temp.trim();

match trimmed.parse::<f32>()
Ok(_) => return trimmed.to_string(),
Err(_) => println!("Not a number!"),
;





I see couple of another problems in your code.



let temp = String::new();


Should be let mut temp, because you'd like to borrow mutable reference later (&mut temp in the read_line call).



Another issue is the loop & read_line. read_line appends to the String. Run this code ...



let mut temp = "foo".to_string();
io::stdin().read_line(&mut temp).unwrap();
println!("-><-", temp);


... and enter 10 for example. You'll see following output ...



->foo10
<-


... which is not what you want. I'd rewrite gettemp() in this way:



fn gettemp() -> f32 
loop
println!("What is your temperature?");

let mut temp = String::new();
io::stdin()
.read_line(&mut temp)
.expect("Failed to read the line");

match temp.trim().parse()
Ok(temp) => return temp,
Err(_) => println!("Not a number!"),
;




IMHO explicit return temp is much cleaner & readable (compared to suggested break out of the loop with a value).




A3 - Why we don't need to explicitly state <f32> in temp.trim().parse()



It's inferred by the compiler.



fn gettemp() -> f32 // 1. f32 is return type
loop
println!("What is your temperature?");

let mut temp = String::new();
io::stdin()
.read_line(&mut temp)
.expect("Failed to read the line");

match temp.trim().parse() ;








share|improve this answer














share|improve this answer



share|improve this answer








edited Mar 10 at 9:22

























answered Mar 7 at 19:08









zrzkazrzka

9,75933258




9,75933258












  • My question is why we don't need to explicitly state <f32> in 'temp.trim().parse()' I looked at documentation that states "Parses this string slice into another type." Can you elaborate on this, please?

    – Julia O
    Mar 10 at 4:22











  • @JuliaO I updated my answer. Check the A3 - Why we don't need to explicitly state <f32> in temp.trim().parse() at the end.

    – zrzka
    Mar 10 at 9:23

















  • My question is why we don't need to explicitly state <f32> in 'temp.trim().parse()' I looked at documentation that states "Parses this string slice into another type." Can you elaborate on this, please?

    – Julia O
    Mar 10 at 4:22











  • @JuliaO I updated my answer. Check the A3 - Why we don't need to explicitly state <f32> in temp.trim().parse() at the end.

    – zrzka
    Mar 10 at 9:23
















My question is why we don't need to explicitly state <f32> in 'temp.trim().parse()' I looked at documentation that states "Parses this string slice into another type." Can you elaborate on this, please?

– Julia O
Mar 10 at 4:22





My question is why we don't need to explicitly state <f32> in 'temp.trim().parse()' I looked at documentation that states "Parses this string slice into another type." Can you elaborate on this, please?

– Julia O
Mar 10 at 4:22













@JuliaO I updated my answer. Check the A3 - Why we don't need to explicitly state <f32> in temp.trim().parse() at the end.

– zrzka
Mar 10 at 9:23





@JuliaO I updated my answer. Check the A3 - Why we don't need to explicitly state <f32> in temp.trim().parse() at the end.

– zrzka
Mar 10 at 9:23













1














Regarding question 1, you can break out of the loop with a value:



fn gettemp() -> f32 
let mut temp = String::new();

loop
println!("What is your temperature?");

io::stdin().read_line(&mut temp).expect("Failed to read the line");

let temp = temp.trim().parse::<f32>();

if !temp.is_ok()
println!("Not a number!");
else
break temp.unwrap() // yield value when breaking out of loop





This way, the whole loop's value is the thing you passed along with break.



Regarding question 2, I am not sure if you really want to do this, because &str is a borrowed type. I think you want to return an String in this case which owns the data.






share|improve this answer























  • Thanks for your comment @phimuemue. What is the difference between 'return' and 'break' with return value? Either makes any difference?

    – Julia O
    Mar 10 at 3:12











  • @JuliaO return returns from the whole function, while break prematurely exits a loop.

    – phimuemue
    Mar 10 at 13:43















1














Regarding question 1, you can break out of the loop with a value:



fn gettemp() -> f32 
let mut temp = String::new();

loop
println!("What is your temperature?");

io::stdin().read_line(&mut temp).expect("Failed to read the line");

let temp = temp.trim().parse::<f32>();

if !temp.is_ok()
println!("Not a number!");
else
break temp.unwrap() // yield value when breaking out of loop





This way, the whole loop's value is the thing you passed along with break.



Regarding question 2, I am not sure if you really want to do this, because &str is a borrowed type. I think you want to return an String in this case which owns the data.






share|improve this answer























  • Thanks for your comment @phimuemue. What is the difference between 'return' and 'break' with return value? Either makes any difference?

    – Julia O
    Mar 10 at 3:12











  • @JuliaO return returns from the whole function, while break prematurely exits a loop.

    – phimuemue
    Mar 10 at 13:43













1












1








1







Regarding question 1, you can break out of the loop with a value:



fn gettemp() -> f32 
let mut temp = String::new();

loop
println!("What is your temperature?");

io::stdin().read_line(&mut temp).expect("Failed to read the line");

let temp = temp.trim().parse::<f32>();

if !temp.is_ok()
println!("Not a number!");
else
break temp.unwrap() // yield value when breaking out of loop





This way, the whole loop's value is the thing you passed along with break.



Regarding question 2, I am not sure if you really want to do this, because &str is a borrowed type. I think you want to return an String in this case which owns the data.






share|improve this answer













Regarding question 1, you can break out of the loop with a value:



fn gettemp() -> f32 
let mut temp = String::new();

loop
println!("What is your temperature?");

io::stdin().read_line(&mut temp).expect("Failed to read the line");

let temp = temp.trim().parse::<f32>();

if !temp.is_ok()
println!("Not a number!");
else
break temp.unwrap() // yield value when breaking out of loop





This way, the whole loop's value is the thing you passed along with break.



Regarding question 2, I am not sure if you really want to do this, because &str is a borrowed type. I think you want to return an String in this case which owns the data.







share|improve this answer












share|improve this answer



share|improve this answer










answered Mar 7 at 13:14









phimuemuephimuemue

20.8k66399




20.8k66399












  • Thanks for your comment @phimuemue. What is the difference between 'return' and 'break' with return value? Either makes any difference?

    – Julia O
    Mar 10 at 3:12











  • @JuliaO return returns from the whole function, while break prematurely exits a loop.

    – phimuemue
    Mar 10 at 13:43

















  • Thanks for your comment @phimuemue. What is the difference between 'return' and 'break' with return value? Either makes any difference?

    – Julia O
    Mar 10 at 3:12











  • @JuliaO return returns from the whole function, while break prematurely exits a loop.

    – phimuemue
    Mar 10 at 13:43
















Thanks for your comment @phimuemue. What is the difference between 'return' and 'break' with return value? Either makes any difference?

– Julia O
Mar 10 at 3:12





Thanks for your comment @phimuemue. What is the difference between 'return' and 'break' with return value? Either makes any difference?

– Julia O
Mar 10 at 3:12













@JuliaO return returns from the whole function, while break prematurely exits a loop.

– phimuemue
Mar 10 at 13:43





@JuliaO return returns from the whole function, while break prematurely exits a loop.

– phimuemue
Mar 10 at 13:43











0














In your program, loop ... creates a new scope. The scope of the second temp starts where it's defined and ends when loop ends. See the following example:



fn main() 
let a = 1;

let a = 2;
println!("", a);

println!("", a);



This prints 2, 1。



If you want to return a string, use (the code is fixed according to the comment below):



fn gettemp() -> String 
loop
let mut temp = String::new();
println!("What is your temperature?");
std::io::stdin().read_line(&mut temp).expect("Failed to read the line");
temp = temp.trim().to_string();
match temp.parse::<f32>()
Err(_) => println!("Not a number!"),
_ => return temp,





&str is a borrowed reference. You cannot return a borrowed reference to a local variable which will be released when the function returns.






share|improve this answer

























  • It's wrong, see my answer. First - read_line appends to the temp - try to enter a<enter>10<enter>. temp will contain an10n and this loop will never end. Second - you're matching temp.trim().parse::<f32>() result and then you're returing untrimmed temp - try to enter 10<enter> and the return value will be "10n", not "10", which isn't probably what you want.

    – zrzka
    Mar 8 at 9:00











  • @zrzka you're right. I didn't realize read_line appends to the buffer.

    – Hong Jiang
    Mar 8 at 10:27















0














In your program, loop ... creates a new scope. The scope of the second temp starts where it's defined and ends when loop ends. See the following example:



fn main() 
let a = 1;

let a = 2;
println!("", a);

println!("", a);



This prints 2, 1。



If you want to return a string, use (the code is fixed according to the comment below):



fn gettemp() -> String 
loop
let mut temp = String::new();
println!("What is your temperature?");
std::io::stdin().read_line(&mut temp).expect("Failed to read the line");
temp = temp.trim().to_string();
match temp.parse::<f32>()
Err(_) => println!("Not a number!"),
_ => return temp,





&str is a borrowed reference. You cannot return a borrowed reference to a local variable which will be released when the function returns.






share|improve this answer

























  • It's wrong, see my answer. First - read_line appends to the temp - try to enter a<enter>10<enter>. temp will contain an10n and this loop will never end. Second - you're matching temp.trim().parse::<f32>() result and then you're returing untrimmed temp - try to enter 10<enter> and the return value will be "10n", not "10", which isn't probably what you want.

    – zrzka
    Mar 8 at 9:00











  • @zrzka you're right. I didn't realize read_line appends to the buffer.

    – Hong Jiang
    Mar 8 at 10:27













0












0








0







In your program, loop ... creates a new scope. The scope of the second temp starts where it's defined and ends when loop ends. See the following example:



fn main() 
let a = 1;

let a = 2;
println!("", a);

println!("", a);



This prints 2, 1。



If you want to return a string, use (the code is fixed according to the comment below):



fn gettemp() -> String 
loop
let mut temp = String::new();
println!("What is your temperature?");
std::io::stdin().read_line(&mut temp).expect("Failed to read the line");
temp = temp.trim().to_string();
match temp.parse::<f32>()
Err(_) => println!("Not a number!"),
_ => return temp,





&str is a borrowed reference. You cannot return a borrowed reference to a local variable which will be released when the function returns.






share|improve this answer















In your program, loop ... creates a new scope. The scope of the second temp starts where it's defined and ends when loop ends. See the following example:



fn main() 
let a = 1;

let a = 2;
println!("", a);

println!("", a);



This prints 2, 1。



If you want to return a string, use (the code is fixed according to the comment below):



fn gettemp() -> String 
loop
let mut temp = String::new();
println!("What is your temperature?");
std::io::stdin().read_line(&mut temp).expect("Failed to read the line");
temp = temp.trim().to_string();
match temp.parse::<f32>()
Err(_) => println!("Not a number!"),
_ => return temp,





&str is a borrowed reference. You cannot return a borrowed reference to a local variable which will be released when the function returns.







share|improve this answer














share|improve this answer



share|improve this answer








edited Mar 8 at 10:29

























answered Mar 8 at 3:28









Hong JiangHong Jiang

1,76811011




1,76811011












  • It's wrong, see my answer. First - read_line appends to the temp - try to enter a<enter>10<enter>. temp will contain an10n and this loop will never end. Second - you're matching temp.trim().parse::<f32>() result and then you're returing untrimmed temp - try to enter 10<enter> and the return value will be "10n", not "10", which isn't probably what you want.

    – zrzka
    Mar 8 at 9:00











  • @zrzka you're right. I didn't realize read_line appends to the buffer.

    – Hong Jiang
    Mar 8 at 10:27

















  • It's wrong, see my answer. First - read_line appends to the temp - try to enter a<enter>10<enter>. temp will contain an10n and this loop will never end. Second - you're matching temp.trim().parse::<f32>() result and then you're returing untrimmed temp - try to enter 10<enter> and the return value will be "10n", not "10", which isn't probably what you want.

    – zrzka
    Mar 8 at 9:00











  • @zrzka you're right. I didn't realize read_line appends to the buffer.

    – Hong Jiang
    Mar 8 at 10:27
















It's wrong, see my answer. First - read_line appends to the temp - try to enter a<enter>10<enter>. temp will contain an10n and this loop will never end. Second - you're matching temp.trim().parse::<f32>() result and then you're returing untrimmed temp - try to enter 10<enter> and the return value will be "10n", not "10", which isn't probably what you want.

– zrzka
Mar 8 at 9:00





It's wrong, see my answer. First - read_line appends to the temp - try to enter a<enter>10<enter>. temp will contain an10n and this loop will never end. Second - you're matching temp.trim().parse::<f32>() result and then you're returing untrimmed temp - try to enter 10<enter> and the return value will be "10n", not "10", which isn't probably what you want.

– zrzka
Mar 8 at 9:00













@zrzka you're right. I didn't realize read_line appends to the buffer.

– Hong Jiang
Mar 8 at 10:27





@zrzka you're right. I didn't realize read_line appends to the buffer.

– Hong Jiang
Mar 8 at 10:27

















draft saved

draft discarded
















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid


  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55043020%2fscope-of-let-with-shadowing-and-string-str-conversion%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

1928 у кіно

Захаров Федір Захарович

Ель Греко