Move a single entry that meets a predicate out of a HashMap when the key is not clonableHow to iterate through a Hashmap, print the key/value and remove the value in Rust?Removing items from a BTreeMap or BTreeSet found through iterationRust loop on HashMap while borrowing selfWhat happens when a duplicate key is put into a HashMap?How does Java HashMap store entries internallymodify field of a struct while pattern matching on itReturning a reference from a HashMap or Vec causes a borrow to last beyond the scope it's in?Rust Implement Methods — Borrow with “getter” method inside mutable borrow methodHow can I replace the value inside a Mutex?Swapping values between two hashmapsModifying HashMap in Rust (mutable borrow occurs here)How can I mutate other elements of a HashMap when using the entry pattern?Is there a way to use the value of an element from a map to update another element without interior mutability?
How does the UK House of Commons think they can prolong the deadline of Brexit?
Why are all volatile liquids combustible
Is the Levitate spell supposed to basically disable a melee-based enemy?
Is there any reason to change the ISO manually?
Round away from zero
How many people can lift Thor's hammer?
Why is a pressure canner needed when canning?
How can I oppose my advisor granting gift authorship to a collaborator?
Can anyone find an image of Henry Bolingbroke's Sovereygne Feather Seal?
If magnetic force can't do any work, then how can we define a potential?
How do I delete cookies from a specific site?
Project Euler Problem 45
Were the women of Travancore, India, taxed for covering their breasts by breast size?
Global variables and information security
Why do we need explainable AI?
Who are these people in this satirical cartoon of the Congress of Verona?
Why does the UK Prime Minister need the permission of Parliament to call a general election?
First Number to Contain Each Letter
How do I anonymously report the Establishment Clause being broken?
Zermelo's proof for unique factorisation
Does POSIX guarantee the paths to any standard utilities?
GFI outlets tripped after power outage
Do we know what "hardness" of Brexit people actually wanted in the referendum, if there had been other choices available?
Does blackhole merging breaks their event horizon seggregation?
Move a single entry that meets a predicate out of a HashMap when the key is not clonable
How to iterate through a Hashmap, print the key/value and remove the value in Rust?Removing items from a BTreeMap or BTreeSet found through iterationRust loop on HashMap while borrowing selfWhat happens when a duplicate key is put into a HashMap?How does Java HashMap store entries internallymodify field of a struct while pattern matching on itReturning a reference from a HashMap or Vec causes a borrow to last beyond the scope it's in?Rust Implement Methods — Borrow with “getter” method inside mutable borrow methodHow can I replace the value inside a Mutex?Swapping values between two hashmapsModifying HashMap in Rust (mutable borrow occurs here)How can I mutate other elements of a HashMap when using the entry pattern?Is there a way to use the value of an element from a map to update another element without interior mutability?
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;
I'm writing a function that works with a HashMap
and at various points in the function I want to check if any of the values in the map meet a condition and if any does return the key for just one of the entries that meets the condition.
So far, I tried to first iterate over references to check my condition, and then use remove_entry
to get an owned copy of the key rather than a borrow:
use std::collections::HashMap, hash::Hash;
fn remove_first_odd<K: Hash + Eq>(map: &mut HashMap<K, u64>) -> Option<K> (_, &value)
but this fails borrow checking, because I can't mutate the map while I am still holding a reference to one of the keys in it:
error[E0502]: cannot borrow `*map` as mutable because it is also borrowed as immutable
--> src/lib.rs:8:45
|
4 | let maybe_entry = map.iter().find(|(_, &value)| value & 1 == 1);
| --- immutable borrow occurs here
...
8 | let (key_owned, _value_owned) = map.remove_entry(key_ref).unwrap();
| ^^^^------------^^^^^^^^^
| | |
| | immutable borrow later used by call
| mutable borrow occurs here
I believe that this is possible, because as long as remove_entry
only dereferences my key before mutation and not after, this should be sound.
So is there a safe API to do this? If not, can one be created?
Note that:
- I can't clone my keys because they are generic without a clone bound
- I can't consume the
HashMap
with something like.into_iter()
- I only need to remove a single entry, not all of the entries that match
rust hashmap borrow-checker
add a comment |
I'm writing a function that works with a HashMap
and at various points in the function I want to check if any of the values in the map meet a condition and if any does return the key for just one of the entries that meets the condition.
So far, I tried to first iterate over references to check my condition, and then use remove_entry
to get an owned copy of the key rather than a borrow:
use std::collections::HashMap, hash::Hash;
fn remove_first_odd<K: Hash + Eq>(map: &mut HashMap<K, u64>) -> Option<K> (_, &value)
but this fails borrow checking, because I can't mutate the map while I am still holding a reference to one of the keys in it:
error[E0502]: cannot borrow `*map` as mutable because it is also borrowed as immutable
--> src/lib.rs:8:45
|
4 | let maybe_entry = map.iter().find(|(_, &value)| value & 1 == 1);
| --- immutable borrow occurs here
...
8 | let (key_owned, _value_owned) = map.remove_entry(key_ref).unwrap();
| ^^^^------------^^^^^^^^^
| | |
| | immutable borrow later used by call
| mutable borrow occurs here
I believe that this is possible, because as long as remove_entry
only dereferences my key before mutation and not after, this should be sound.
So is there a safe API to do this? If not, can one be created?
Note that:
- I can't clone my keys because they are generic without a clone bound
- I can't consume the
HashMap
with something like.into_iter()
- I only need to remove a single entry, not all of the entries that match
rust hashmap borrow-checker
3
"I can't clone my keys" in which world ? I don't think you can in safe mode.
– Stargateur
Mar 28 at 5:01
1
I'm afraid it's not possible, at least not if you want to return the key which has been removed. If you do not need to return the value you could useretain
to remove the pair that fits your criteria.
– hellow
Mar 28 at 7:15
@Stargateur I edited it to make it more clear
– timotree
Mar 28 at 12:10
@timotree so let me be more clear, key in a hashmap should be clonable in 99% of use case. That very odd situation you have here. I advice you to describe why you can't clone the key.
– Stargateur
Mar 28 at 12:13
1
See also How to iterate through a Hashmap, print the key/value and remove the value in Rust?; Removing items from a BTreeMap or BTreeSet found through iteration; Rust loop on HashMap while borrowing self;
– Shepmaster
Mar 31 at 18:34
add a comment |
I'm writing a function that works with a HashMap
and at various points in the function I want to check if any of the values in the map meet a condition and if any does return the key for just one of the entries that meets the condition.
So far, I tried to first iterate over references to check my condition, and then use remove_entry
to get an owned copy of the key rather than a borrow:
use std::collections::HashMap, hash::Hash;
fn remove_first_odd<K: Hash + Eq>(map: &mut HashMap<K, u64>) -> Option<K> (_, &value)
but this fails borrow checking, because I can't mutate the map while I am still holding a reference to one of the keys in it:
error[E0502]: cannot borrow `*map` as mutable because it is also borrowed as immutable
--> src/lib.rs:8:45
|
4 | let maybe_entry = map.iter().find(|(_, &value)| value & 1 == 1);
| --- immutable borrow occurs here
...
8 | let (key_owned, _value_owned) = map.remove_entry(key_ref).unwrap();
| ^^^^------------^^^^^^^^^
| | |
| | immutable borrow later used by call
| mutable borrow occurs here
I believe that this is possible, because as long as remove_entry
only dereferences my key before mutation and not after, this should be sound.
So is there a safe API to do this? If not, can one be created?
Note that:
- I can't clone my keys because they are generic without a clone bound
- I can't consume the
HashMap
with something like.into_iter()
- I only need to remove a single entry, not all of the entries that match
rust hashmap borrow-checker
I'm writing a function that works with a HashMap
and at various points in the function I want to check if any of the values in the map meet a condition and if any does return the key for just one of the entries that meets the condition.
So far, I tried to first iterate over references to check my condition, and then use remove_entry
to get an owned copy of the key rather than a borrow:
use std::collections::HashMap, hash::Hash;
fn remove_first_odd<K: Hash + Eq>(map: &mut HashMap<K, u64>) -> Option<K> (_, &value)
but this fails borrow checking, because I can't mutate the map while I am still holding a reference to one of the keys in it:
error[E0502]: cannot borrow `*map` as mutable because it is also borrowed as immutable
--> src/lib.rs:8:45
|
4 | let maybe_entry = map.iter().find(|(_, &value)| value & 1 == 1);
| --- immutable borrow occurs here
...
8 | let (key_owned, _value_owned) = map.remove_entry(key_ref).unwrap();
| ^^^^------------^^^^^^^^^
| | |
| | immutable borrow later used by call
| mutable borrow occurs here
I believe that this is possible, because as long as remove_entry
only dereferences my key before mutation and not after, this should be sound.
So is there a safe API to do this? If not, can one be created?
Note that:
- I can't clone my keys because they are generic without a clone bound
- I can't consume the
HashMap
with something like.into_iter()
- I only need to remove a single entry, not all of the entries that match
rust hashmap borrow-checker
rust hashmap borrow-checker
edited Mar 31 at 18:28
Shepmaster
179k22 gold badges395 silver badges560 bronze badges
179k22 gold badges395 silver badges560 bronze badges
asked Mar 28 at 3:44
timotreetimotree
5052 silver badges20 bronze badges
5052 silver badges20 bronze badges
3
"I can't clone my keys" in which world ? I don't think you can in safe mode.
– Stargateur
Mar 28 at 5:01
1
I'm afraid it's not possible, at least not if you want to return the key which has been removed. If you do not need to return the value you could useretain
to remove the pair that fits your criteria.
– hellow
Mar 28 at 7:15
@Stargateur I edited it to make it more clear
– timotree
Mar 28 at 12:10
@timotree so let me be more clear, key in a hashmap should be clonable in 99% of use case. That very odd situation you have here. I advice you to describe why you can't clone the key.
– Stargateur
Mar 28 at 12:13
1
See also How to iterate through a Hashmap, print the key/value and remove the value in Rust?; Removing items from a BTreeMap or BTreeSet found through iteration; Rust loop on HashMap while borrowing self;
– Shepmaster
Mar 31 at 18:34
add a comment |
3
"I can't clone my keys" in which world ? I don't think you can in safe mode.
– Stargateur
Mar 28 at 5:01
1
I'm afraid it's not possible, at least not if you want to return the key which has been removed. If you do not need to return the value you could useretain
to remove the pair that fits your criteria.
– hellow
Mar 28 at 7:15
@Stargateur I edited it to make it more clear
– timotree
Mar 28 at 12:10
@timotree so let me be more clear, key in a hashmap should be clonable in 99% of use case. That very odd situation you have here. I advice you to describe why you can't clone the key.
– Stargateur
Mar 28 at 12:13
1
See also How to iterate through a Hashmap, print the key/value and remove the value in Rust?; Removing items from a BTreeMap or BTreeSet found through iteration; Rust loop on HashMap while borrowing self;
– Shepmaster
Mar 31 at 18:34
3
3
"I can't clone my keys" in which world ? I don't think you can in safe mode.
– Stargateur
Mar 28 at 5:01
"I can't clone my keys" in which world ? I don't think you can in safe mode.
– Stargateur
Mar 28 at 5:01
1
1
I'm afraid it's not possible, at least not if you want to return the key which has been removed. If you do not need to return the value you could use
retain
to remove the pair that fits your criteria.– hellow
Mar 28 at 7:15
I'm afraid it's not possible, at least not if you want to return the key which has been removed. If you do not need to return the value you could use
retain
to remove the pair that fits your criteria.– hellow
Mar 28 at 7:15
@Stargateur I edited it to make it more clear
– timotree
Mar 28 at 12:10
@Stargateur I edited it to make it more clear
– timotree
Mar 28 at 12:10
@timotree so let me be more clear, key in a hashmap should be clonable in 99% of use case. That very odd situation you have here. I advice you to describe why you can't clone the key.
– Stargateur
Mar 28 at 12:13
@timotree so let me be more clear, key in a hashmap should be clonable in 99% of use case. That very odd situation you have here. I advice you to describe why you can't clone the key.
– Stargateur
Mar 28 at 12:13
1
1
See also How to iterate through a Hashmap, print the key/value and remove the value in Rust?; Removing items from a BTreeMap or BTreeSet found through iteration; Rust loop on HashMap while borrowing self;
– Shepmaster
Mar 31 at 18:34
See also How to iterate through a Hashmap, print the key/value and remove the value in Rust?; Removing items from a BTreeMap or BTreeSet found through iteration; Rust loop on HashMap while borrowing self;
– Shepmaster
Mar 31 at 18:34
add a comment |
0
active
oldest
votes
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55389847%2fmove-a-single-entry-that-meets-a-predicate-out-of-a-hashmap-when-the-key-is-not%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
0
active
oldest
votes
0
active
oldest
votes
active
oldest
votes
active
oldest
votes
Is this question similar to what you get asked at work? Learn more about asking and sharing private information with your coworkers using Stack Overflow for Teams.
Is this question similar to what you get asked at work? Learn more about asking and sharing private information with your coworkers using Stack Overflow for Teams.
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55389847%2fmove-a-single-entry-that-meets-a-predicate-out-of-a-hashmap-when-the-key-is-not%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
3
"I can't clone my keys" in which world ? I don't think you can in safe mode.
– Stargateur
Mar 28 at 5:01
1
I'm afraid it's not possible, at least not if you want to return the key which has been removed. If you do not need to return the value you could use
retain
to remove the pair that fits your criteria.– hellow
Mar 28 at 7:15
@Stargateur I edited it to make it more clear
– timotree
Mar 28 at 12:10
@timotree so let me be more clear, key in a hashmap should be clonable in 99% of use case. That very odd situation you have here. I advice you to describe why you can't clone the key.
– Stargateur
Mar 28 at 12:13
1
See also How to iterate through a Hashmap, print the key/value and remove the value in Rust?; Removing items from a BTreeMap or BTreeSet found through iteration; Rust loop on HashMap while borrowing self;
– Shepmaster
Mar 31 at 18:34