alexcrichton / curl-rust

Rust bindings to libcurl
MIT License
1k stars 234 forks source link

one of your examples doesnt work #526

Open lever1209 opened 10 months ago

lever1209 commented 10 months ago
use curl::easy::Easy;

// Capture output into a local `Vec`.
fn main() {
    let mut dst = Vec::new();
    let mut easy = Easy::new();
    easy.url("https://www.rust-lang.org/").unwrap();

    let mut transfer = easy.transfer();
    transfer.write_function(|data| {
        dst.extend_from_slice(data);
        Ok(data.len())
    }).unwrap();
    transfer.perform().unwrap();
    println!("{:?}", dst);
}

ive added that last println! line as a basic way to show theres no way to access the data after its written to, unless im missing something fundamental about closures

sagebind commented 10 months ago

The closure passed to write_function borrows dst. The transfer object holds onto that closure until the transfer is dropped, meaning that dst is also now borrowed until transfer is dropped. To access dst you need to ensure the transfer is dropped to guarantee it will not write any further to dst. In this short example you could do that like this:

use curl::easy::Easy;

// Capture output into a local `Vec`.
fn main() {
    let mut dst = Vec::new();
    let mut easy = Easy::new();
    easy.url("https://www.rust-lang.org/").unwrap();

    {
        let mut transfer = easy.transfer();
        transfer.write_function(|data| {
            dst.extend_from_slice(data);
            Ok(data.len())
        }).unwrap();
        transfer.perform().unwrap();
    }

    println!("{:?}", dst);
}

or more explicitly like this:

use curl::easy::Easy;

// Capture output into a local `Vec`.
fn main() {
    let mut dst = Vec::new();
    let mut easy = Easy::new();
    easy.url("https://www.rust-lang.org/").unwrap();

    let mut transfer = easy.transfer();
    transfer.write_function(|data| {
        dst.extend_from_slice(data);
        Ok(data.len())
    }).unwrap();
    transfer.perform().unwrap();
    drop(transfer);

    println!("{:?}", dst);
}

Hope that helps!

lever1209 commented 10 months ago

i already tried that and it didnt work, maybe i missed something

but ive already moved the project to a shell script and its 90% done

LorenzoLeonardo commented 8 months ago

Best to Use Easy2.