2
[indent=4]

init
    x: array of int = {1, 2, 3}
    y: array of int = {4, 5, 6}
    z: array of int = x + y

The above code produces this error message:

concat_arrays.gs:6.23-6.27: error: Incompatible operand
    z: array of int = x + y

The Vala translation doesn't work any better:

int main () {
    int[] x = {1, 2, 3};
    int[] y = {4, 5, 6};
    int[] z = x + y;
    return 0;
}

The error message is:

concat_arrays_v.vala:4.15-4.19: error: Incompatible operand
    int[] z = x + y;

What is the correct way to do this?

Jens Mühlenhoff
  • 14,565
  • 6
  • 56
  • 113

1 Answers1

1

Using GLib.Array<T>:

int main () {
    int[] x = {1, 2, 3};
    int[] y = {4, 5, 6};
    Array<int> a = new Array<int> (false, true, 0);
    a.append_vals (x, x.length);
    a.append_vals (y, y.length);
    // taking over ownership avoids array copying
    int[] z = (owned) a.data; 

    foreach (var i in z) {
        stdout.printf ("%d ", i);
    }
    stdout.printf ("\n");

    return 0;
}

The Genie version:

[indent=4]

init
    x: array of int = {1, 2, 3}
    y: array of int = {4, 5, 6}
    var a = new Array of int (false, true, 0)
    a.append_vals (x, x.length)
    a.append_vals (y, y.length)
    z: array of int = (owned) a.data

Update: After answering this question I have modified the above code to use (owned) which avoids an uneccessary array copy operation.

The new Array<T> still adds some overhead for allocating an object, but that should be no problem in most cases.

Using Memory.copy is dangerous as it can cause all sorts of memory problems.

Community
  • 1
  • 1
Jens Mühlenhoff
  • 14,565
  • 6
  • 56
  • 113
  • Is this still the way to got? Looks complicated to just append one array to another. – aggsol Feb 28 '20 at 09:47
  • It is the easiest way to add two plain arrays that I know of, yes. There are more flexible data types you can use though like Gee.ArrayList (which has a add_all () method). – Jens Mühlenhoff Feb 28 '20 at 11:16