[Solved] As main fn, it compiles, but as non-main fn, it doesn't?

First attempt at Rust beyond hello world, and I'm tripping over this:

extern crate reqwest;
use std::collections::HashMap;

fn request(terminal_id: String) -> () {
  let url = format!("https://httpbin.org/ip");
  let resp: HashMap<String, String> = reqwest::get(url.as_str())?.json()?; // This errors?  Why?
  println!("{:#?}", resp);
}

fn main() -> Result<(), Box<std::error::Error>> {
  let url = format!("https://httpbin.org/ip");
  let resp: HashMap<String, String> = reqwest::get(url.as_str())?.json()?;
  println!("{:#?}", resp);
  Ok(())
}

If it's just the main function, the program will run. But as soon as I try to break it out into a function, it won't compile - what is going on???

What's the error message?
By chance is it

error[E0277]: the `?` operator can only be used in a function that returns `Result` or `Option` (or another type that implements `std::ops::Try`)
 --> src/main.rs:6:39
  |
6 |   let resp: HashMap<String, String> = reqwest::get(url.as_str())?.json()?; // This errors?  Why?
  |                                       ^^^^^^^^^^^^^^^^^^^^^^^^^^^ cannot use the `?` operator in a function that returns `()`
  |
  = help: the trait `std::ops::Try` is not implemented for `()`
  = note: required by `std::ops::Try::from_error`

error[E0277]: the `?` operator can only be used in a function that returns `Result` or `Option` (or another type that implements `std::ops::Try`)
 --> src/main.rs:6:39
  |
6 |   let resp: HashMap<String, String> = reqwest::get(url.as_str())?.json()?; // This errors?  Why?
  |                                       ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ cannot use the `?` operator in a function that returns `()`
  |
  = help: the trait `std::ops::Try` is not implemented for `()`
  = note: required by `std::ops::Try::from_error`

Note that usage of the ? operator requires that the function returns a Result, because it is a smart unwrapper for results
You can fix this by changing the return type of the function:

fn request(terminal_id: String) -> Option<Box<std::error::Error>> {

Docs

Yes, that is exactly it, that gets me going in the right direction. Thank you!

This topic was automatically closed after 27 hours. New replies are no longer allowed.