how to return an array of unowned strings that all point to the same location in memory?
example:
init
var str = "ABC"
var unowned_string_array = repeat (str, 5)
def repeat (s: string, n: int): array of string
// code
and this array will contains 5 elements(same string "ABC"), all point to same location
The closest Vala code I could get is:
int main() {
var str = "ABC";
var unowned_string_array = repeat (str, 5);
return 0;
}
public (unowned string)[] repeat (string s, int n) {
var a = new (unowned string)[n];
for (var i = 0; i < n; i++)
// This sadly still duplicates the string,
// even though a should be an array of unowned strings
a[i] = s;
return a;
}
I'm not sure if the compiler understands the parenthesis here, it may think that I want to declare an unowned array of owned strings here ...
Update: It turns out the problem is that type inference will always create an owned variable (see nemequs comment).
There is even a bug report for this.
So this works just fine (no string duplication in the repeat
function):
int main() {
var str = "ABC";
(unowned string)[] unowned_string_array = repeat (str, 5);
return 0;
}
public (unowned string)[] repeat (string s, int n) {
(unowned string)[] a = new (unowned string)[n];
for (var i = 0; i < n; i++)
// This sadly still duplicates the string,
// even though a should be an array of unowned strings
a[i] = s;
return a;
}
Which would be something like this in Genie:
[indent=4]
init
var str = "ABC"
unowned_string_array: array of (unowned string) = repeat (str, 5)
def repeat (s: string, n: int): array of (unowned string)
a: array of (unowned string) = new array of (unowned string)[n]
for var i = 1 to n
a[i] = s
return a
The Genie code has the additional problem of not compiling, due to the parser not being able to deduce what comes after the array of
.
This seems to be a similar problem to what I already had with nested generic types.
I have reported this a Genie bug.