Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"value is never read" warning that seems to be incorrect. Should I ignore it?

Tags:

rust

I've been programming in Rust for only a few months. That being said, I'm encountering a warning that reads:

warning: value assigned to `amount` is never read
   --> src\execute_action_functions.rs:428:21
    |
428 |             let mut amount: Option<f64> = None;
    |                     ^^^^^^
    |
    = help: maybe it is overwritten before being read?

For clarity and so as to not accidentally miss a key detail, the entire function is below:

pub async fn handle_all_gemini(prefix: &str, message: &str, shared_neural_network: Arc<Mutex<NeuralNetwork>>, divisor: &f64) {


    if prefix.contains("Gemini received") {
        if message.contains("heartbeat") {
            return;
        }
        else {
            let data: Result<Value, serde_json::Error> = serde_json::from_str(message);

            let mut amount: Option<f64> = None;
            let mut price: Option<f64> = None;

            match data {
                Ok(value) => {
                    if value.get("socket_sequence")
                    .and_then(Value::as_i64) == Some(0) {
                        println!("Gemini: socket sequence is 0, ignoring...");
                        return;
                    }
                    if let Value::Object(map) = &value {
                        if let Some(Value::Array(events)) = map
                        .get("events") {
                            if let Some(Value::Object(event)) =
                             events.get(0) {
                                amount = event.get("amount")
                                    .and_then(|v| v.as_str())
                                    .and_then(|s| s.parse::<f64>().ok());
                                price = event.get("price")
                                    .and_then(|v| v.as_str())
                                    .and_then(|s| s.parse::<f64>().ok());
                            } 
                            else {
                                panic!("Gemini: event is not an object.
                                message: {}", message);
                            }
                        } 
                        else {
                            panic!("Gemini: events is not an array.
                            message: {}", message);
                        }
                    } 
                    else {
                        panic!("Gemini: Value is not an object.
                        message: {}", message);
                    }
                },
                Err(e) => {
                    panic!("Failed to parse JSON Gemini message\nError: {}
                    Message: {}", e, message);
                },
            }

            let new_values = [amount, price];
            let mut scaled_values: Vec<f64> = Vec::new();
            for value in &new_values {
                if let Some(val) = value {
                    scaled_values.push(val / divisor);
                } 
                else {
                    println!("One of the values was None");
                    panic!("amount: {:?}, price: {:?}", &amount, &price);
                }
            }
            if prefix.contains("sol") {
                let indices = [58, 59];
                let mut neural_network = 
                    shared_neural_network.lock().await;
                neural_network.update_input(&indices, &scaled_values)
                .await;
            }
            else if prefix.contains("xrp") {
                let indices = [92, 93];
                let mut neural_network = 
                    shared_neural_network.lock().await;
                neural_network.update_input(&indices, &scaled_values)
            .await;
            }
            else {
                panic!("This shouid never occur. Somehow prefix cointained phrase
                Gemini received but didn't contain the phrases XLM or XRP.
                prefix is: {}\nmessage: {}", prefix, message);
            }
        }
    }
    else {
        println!("Gemini: got a weird message: {}\nprefix:{}", message, prefix);
    }
}

As you can see, it's definitely being read at least when new_values is initialized, and in the for-loop as well, if I'm not mistaken.

I tried changing it to amount: Option<f64>; However, I get a very weird warning saying:

warning: variable does not need to be mutable
   --> src\execute_action_functions.rs:429:17
    |
429 |             let mut price: Option<f64>;
    |                 ----^^^^^
    |                 |
    |                 help: remove this `mut`

Which doesn't make any sense because I'm changing the value in if let Value::Object(map) = &value { So, this makes it even more confusing. I'm not sure what I'm doing wrong because I'm not giving it a real value, so there's no "overwritten before read" issue, right? Does it have something to do with the if let? Any help would be greatly appreciated.

like image 850
Jamie Laden Avatar asked Oct 12 '25 15:10

Jamie Laden


1 Answers

You first assign amount to None in the line that you declared it in:

let mut amount: Option<f64> = None;

You later reassign amount here:

amount = event.get("amount")
    .and_then(|v| v.as_str())
    .and_then(|s| s.parse::<f64>().ok());

Afterwards, you read amount here:

let new_values = [amount, price];

The compiler is actually really smart here: All branches of your code that don't reach the second assignment raise a panic, causing them to never reach the subsequent read. Therefore, the compiler is saying that the initial assignment to None is unnecessary, because that value is never read. You can fix this warning by changing the line to:

let amount: Option<f64>; //no initial value here

Because amount is assigned to exactly once (before it is ever read), it does not have to be declared mutable.


It's important to note that this is just a warning, not an error. Your program will still compile and work just fine, the compiler is just telling you that it contains unnecessary logic that might be unintentional.

like image 140
ChrisB Avatar answered Oct 15 '25 20:10

ChrisB