Asked  6 Months ago    Answers:  5   Viewed   19 times

I have a struct with a field:

struct A {
    field: SomeType,
}

Given a &mut A, how can I move the value of field and swap in a new value?

fn foo(a: &mut A) {
    let mut my_local_var = a.field;
    a.field = SomeType::new();

    // ...
    // do things with my_local_var
    // some operations may modify the NEW field's value as well.
}

The end goal would be the equivalent of a get_and_set() operation. I'm not worried about concurrency in this case.

 Answers

29

Use std::mem::swap().

fn foo(a: &mut A) {
    let mut my_local_var = SomeType::new();
    mem::swap(&mut a.field, &mut my_local_var);
}

Or std::mem::replace().

fn foo(a: &mut A) {
    let mut my_local_var = mem::replace(&mut a.field, SomeType::new());
}    
Tuesday, June 1, 2021
 
mdevils
answered 6 Months ago
39
Tok:tmp doug$ du -a

8   ./Cargo.toml
8   ./src/bin.rs
8   ./src/lib.rs
16  ./src

Cargo.toml:

[package]
name = "mything"
version = "0.0.1"
authors = ["me <me@gmail.com>"]

[lib]
name = "mylib"
path = "src/lib.rs"

[[bin]]
name = "mybin"
path = "src/bin.rs"

src/lib.rs:

pub fn test() {
    println!("Test");
}

src/bin.rs:

extern crate mylib; // not needed since Rust edition 2018

use mylib::test;

pub fn main() {
    test();
}
Sunday, June 6, 2021
 
PHPWDev
answered 6 Months ago
74

Print the whole page

Try adding a button that calls window.print()

<input type="button" value="Print this page" onClick="window.print()">

Print a specific portion/container in a page

<div id="print-content">
 <form>

  <input type="button" onclick="printDiv('print-content')" value="print a div!"/>
</form>
</div>

then in the HTML file, add this script code

<script type="text/javascript">
    function printDiv(divName) {
        var printContents = document.getElementById(divName).innerHTML;
        w=window.open();
        w.document.write(printContents);
        w.print();
        w.close();
    }
</script>

Refer Print <div id="printarea"></div> only?

Sunday, August 1, 2021
 
EnTee
answered 4 Months ago
31

I've succeeded to run the non-optimised code without abnormalities. Thanks to Notlikethat for the idea. My stack was just mapped into readonly memory.

So I've just added the offset statement into my linker script (". = 1024M;") in order to make all the symbols to start from 1GiB (where RAM begins). After this modification the code started to work properly.

Monday, August 23, 2021
 
cletus
answered 3 Months ago
50

You need to set autoflush for STDOUT. Example:

use IO::Handle;
STDOUT->autoflush(1);
foreach (1..20) {
  print '.';
  sleep(1);
}
Thursday, October 7, 2021
 
showstealer
answered 2 Months ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :  
Share