Re: [Vala] idiomatic way to pass an array for modification to a function



Hi,

Everything is a reference in Vala, so, there's no buffer copy in your
example.

The rationale is opposite: Everything is passed as reference, if you want
to pass as copy, you have to set the parameter `owned`

```
void change_values(owned int[] w,int loc) { w[loc+0]=1; w[loc+1]=2;
w[loc+2]=3; }
```

Also, since you created an array with `new int[]` you should have an
parameter with the same construction, so that you variable `w` inside
`change_values` will have properties such as `.length`.

On Sun, Dec 27, 2015 at 6:24 PM Dan Hitt <dan hitt gmail com> wrote:

I've been struggling to write a function that can modify an array it
receives as an argument.

Now, as it happens, it looks like you can just write it like it were
C, using pointers.

So this code works and does what i expect:

    void main( ) {
            var t = new int[6];
            change_values(t, 0);
            change_values(t, 3);
            for (var i=0; i<t.length; i++)
                    stdout.printf("%d -> %d\n",i,t[i]);
    }

    void change_values(int *w,int loc) {
            w[loc+0]=1;
            w[loc+1]=2;
            w[loc+2]=3;
    }

However, it doesn't use 'ref' and i would like to write something more
idiomatic.

The constraint is that i really do want to have reference-type semantics
with
no unnecessary copying because the actual application will involve a
routine
called many times on a long input array.

Thanks in advance for any clues on how to make this more stylistic, or any
good
but detailed references.  (This subject seems to come up from time to
time, but the
answers are never quite detailed enough for me to comprehend.)

dan
_______________________________________________
vala-list mailing list
vala-list gnome org
https://mail.gnome.org/mailman/listinfo/vala-list



[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]