'use of moved value error' issue in simple function

Hi, I am new to rust programming language and trying something. If I wrap builder into the Box then I think this problem will be fixed but it didn't work. How I can fix this?

	fn request(self, method: reqwest::Method, url: Url) -> RequestBuilder {
		let mut headers = header::HeaderMap::new();

		headers.insert(
			reqwest::header::COOKIE,
			header::HeaderValue::from_str("cookie").unwrap(),
		);

		let builder = self.client.request(method, url);
		builder.headers(headers);

		builder << use of moved value: `builder`
	}

Because RequestBuilder::headers() consumes self, to make use of the builder pattern. It also returns it, so you can do either:

let builder = self.client.request(method, url);
builder
    .headers(headers)
    .another_method()
    // ...

Or:

let builder = self.client.request(method, url);
let builder = builder.headers(headers);
let builder = builder.another_method();
// ...
1 Like

When a function takes a parameter by value (including self) it takes ownership, and the original variable can no longer be used, unless it happens to implement Copy.

From the documentation, we can see that the RequestBuilder methods like headers take self by value, but also return a RequestBuilder. This is a common style of "builder pattern" so that you can do things like let result = builder.add(this).also_add(that).et(cetera).finish().

So in this case you just need to change:

-		builder.headers(headers);
-		builder // use of moved value: `builder`
+       builder.headers(headers)

(Note that your request method itself also takes self by value, and you may run into the same type of problem again when using it. There's not enough context to be sure, but perhaps you should be taking &self or &mut self.)

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.