Another newb question

How is it possible that this

pub fn load() -> String {
    let contents = fs::read_to_string("src/channels/bin/main.rs").unwrap();
    contents
}

compiles, but this

pub fn load() -> String {
    fs::read_to_string("src/channels/bin/main.rs").unwrap();
}

does not, complaining that () rather than String is returned?!

read_to_string returns a Result, and unwrap obviously unwraps it. Where does the value go in the 2nd case, and how does merely storing it in a local value make it work?

This is odd stuff, I tells ya.

cargo check output (you may have to scroll right to see the pertinent part on the last line):

error[E0308]: mismatched types
 --> src/lib.rs:2:18
  |
2 | pub fn load() -> String {
  |        ----      ^^^^^^ expected `String`, found `()`
  |        |
  |        implicitly returns `()` as its body has no tail or `return` expression
3 |     fs::read_to_string("src/channels/bin/main.rs").unwrap();
  |                                                            - help: remove this semicolon to return this value

You don't have a trailing expression due to the ;. So remove the ;.

This produces a similar error:

pub fn load() -> String {
    let contents = fs::read_to_string("src/channels/bin/main.rs").unwrap();
    //      v added semicolon
    contents;
}
7 Likes

DOH and FFS.

We all make those sorts of error where sometimes we see what we want to see, and a fresh pair of eyes spots it. :slight_smile:

1 Like

Hello,

because you use a semicolon at the end,

either remove the semicolon, or use the return keyword like this :

return fs::read_to_string("src/channels/bin/main.rs").unwrap() ;

exemple :

fn test() -> String {
    let s = "Hello".to_string();
    return s;
}

is equivalent to this

fn test() -> String {
    let s = "Hello".to_string();
    s
}

or

fn test() -> String {
    return "Hello".to_string();
}

or

fn test() -> String {
    "Hello".to_string()
}

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.