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

Breaking the **R**ules: mutable references #22

Open
JosiahParry opened this issue Mar 2, 2024 · 3 comments
Open

Breaking the **R**ules: mutable references #22

JosiahParry opened this issue Mar 2, 2024 · 3 comments

Comments

@JosiahParry
Copy link
Contributor

This could be an advanced section with hazards all over it that discusses how to mutate R objects in place.

This is against the clone on write (Cow) rules of R. BUT if you created and own all of the objects, it may make sense to mutably handle them. in some cases.

@JosiahParry
Copy link
Contributor Author

For example this will let you modify the first element of an integer vector in place

#[extendr]
fn changeme(x: Integers) {
    let mut x = x;
    x[0] = 100.into();
}

@JosiahParry
Copy link
Contributor Author

#[extendr]
fn swap_list_element(x: List, y: Robj, idx: i32) {
    let mut x = x;
    let _ = x.set_elt(idx as usize, y);
}
(o <- list(x = 1, y = 2, z = "a"))
#> $x
#> [1] 1
#> 
#> $y
#> [1] 2
#> 
#> $z
#> [1] "a"

# get address
addr_1 <- tracemem(o)

# swap in place 
swap_list_element(o, letters, 0)

# print 
o
#> $x
#>  [1] "a" "b" "c" "d" "e" "f" "g" "h" "i" "j" "k" "l" "m" "n" "o" "p" "q" "r" "s"
#> [20] "t" "u" "v" "w" "x" "y" "z"
#> 
#> $y
#> [1] 2
#> 
#> $z
#> [1] "a"

# get address again
addr_2 <- tracemem(o)

# check that the addresses are the same 
identical(addr_1, addr_2)
#> [1] TRUE

Created on 2024-03-02 with reprex v2.0.2

@JosiahParry
Copy link
Contributor Author

This could be a cool place to recreate rlang::vec_poke_n() using Rust

@CGMossa CGMossa transferred this issue from extendr/user-guide-old Jun 30, 2024
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

1 participant