Err "value moved here"

Hello there,

i have the error "value moved here" when i try to use a variable like this :

error[E0382]: use of moved value: `postgres_url`
   --> src/main.rs:257:116
    |
227 | 	let db_local = Connection::connect(postgres_url, TlsMode::None)
    | 	                                   ------------ value moved here
...
257 | 		let counter_receive_last_id2= counter_last_entry("SELECT id::bigint from astm_receive order by id desc limit 1",&postgres_url)as i32;
    | 	  

and when i don't borrow the variable (using only the string) i have this kind of error.

   --> src/main.rs:237:117
    |
237 | 	let mut counter_receive_last_id= counter_last_entry("SELECT id::bigint from astm_receive order by id desc limit 1",postgres_url)as i32;
    | 	                                                                                                                   ^^^^^^^^^^^^ expected &str, found struct `std::string::String`
    |
    = note: expected type `&str`
               found type `std::string::String`
    = help: try with `&postgres_url`

the postgres_url is formated as a String.

Any help plz ? :slight_smile:

Thanks !

Connection::connect takes ownership of your postgres_url. You cannot use it afterwards. You need to .clone() it.

Take a look at how connect is defined - it requires an argument that implements IntoConnectParams, which contains only a single method that accepts self via move.

Pass &postgres_url, which will be a string slice for which there's an impl of IntoConnectParams - it won't move your String value then, and you can continue using it.

2 Likes

To add to previous answers, in Rust there are pairs of "owned" and "borrowed" types:

  • &str and String
  • &[] and Vec
  • &Path and PathBuf

and many more. If you have an owned type like String, you can make it look like a borrowed one (&str) by taking a reference.

let s: String = String::from("hello");
let s: &str = &s;