Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass pointer to a container from function?

Tags:

raku

I can bind containers to new names:

my %h;
my $p := %h{ "a" }{ "b" }{ "c" };
$p = 1;
say %h;

Which outputs expected:

{a => {b => {c => 1}}}

But what if I need to return such pointer from subroutine?

my %h;
sub get-pointer {
    my $p := %h{ "a" }{ "b" }{ "c" };
    return $p;
};
my $q := get-pointer();
$q = 1;
say %h;

Gives:

Cannot assign to a readonly variable or a value

That thing puzzles me - $p.WHERE and $q.WHERE give the same address, so why is it suddenly read-only?

like image 512
Pawel Pabian bbkr Avatar asked Jan 11 '21 22:01

Pawel Pabian bbkr


People also ask

How do you pass pointers to a function?

C programming allows passing a pointer to a function. To do so, simply declare the function parameter as a pointer type.

Can a pointer be passed by value?

Yes to both. Pointers are passed by value as anything else. That means the contents of the pointer variable (the address of the object pointed to) is copied.

How do you pass a pointer to an address?

If you declare a formal parameter of a function as a pointer type, you are passing that parameter by its address. The pointer is copied, but not the data it points to. So, Pass By Address offers another method of allowing us to change the original argument of a function (like with Pass By Reference).

Can we pass pointer as an argument to function?

Just like any other argument, pointers can also be passed to a function as an argument.


1 Answers

Nevermind, I had some tunnel-vision moment and wanted aliases to behave as C pointers.

Found it clearly explained here at Raku Documentation.

The sub return will return values, not containers. Those are immutable

To return a mutable container, use return-rw.

like image 87
Pawel Pabian bbkr Avatar answered Nov 20 '22 00:11

Pawel Pabian bbkr