Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type `usize` cannot be dereferenced

I've got some code that looks somewhat like the following:

let incoming: Vec<u8> = Vec::new();

match some_function(|data| {
    let temp = &mut incoming;
    Ok(*temp.write(data).unwrap())
}) {
    Ok(v) => v,
    Err(err) => return false,
};

Now the error I'm getting is the following:

error: type `usize` cannot be dereferenced
   --> src/stripe_connection.rs:127:16
     |
 127 |             Ok(*temp.write(data).unwrap())

For some reason I can't get my head around what I'm doing wrong, as the borrowing/lifecycle is still very new to me.

like image 730
Joseph Callaars Avatar asked Dec 03 '22 23:12

Joseph Callaars


2 Answers

usize doesn't implement the Deref trait, so you can't apply * to it. write() returns a Result<usize>, so when you unwrap() it and apply the dereferencing asterisk:

*temp.write(data).unwrap()

You are attempting to do

*usize

Which is not possible.

like image 32
ljedrz Avatar answered Jan 12 '23 23:01

ljedrz


I think you may be getting the operator precedence wrong.

*temp.write(data).unwrap() is equivalent to *(temp.write(data).unwrap()), not to (*temp).write(data).unwrap(). You could write the latter, but it's unnecessary, because the compiler will automatically dereference pointers in the subject of a method call (i.e. the x in x.f(..)). So you should just remove the * altogether here.

like image 142
Francis Gagné Avatar answered Jan 12 '23 23:01

Francis Gagné