Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

one of your examples doesnt work #526

Open
lever1209 opened this issue Aug 20, 2023 · 3 comments
Open

one of your examples doesnt work #526

lever1209 opened this issue Aug 20, 2023 · 3 comments

Comments

@lever1209
Copy link

lever1209 commented Aug 20, 2023

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
Copy link
Collaborator

sagebind commented Aug 21, 2023

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
Copy link
Author

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
Copy link
Contributor

Best to Use Easy2.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants