精灵如何 return 一个无主字符串数组

Genie how to return an array of unowned strings

如何return 数组 无主字符串 都指向内存中的相同位置?

示例:

init
    var str = "ABC"
    var unowned_string_array = repeat (str, 5)

def repeat (s: string, n: int): array of string
    // code

这个数组将包含 5 个元素(相同的字符串 "ABC"),都指向相同的位置

我能得到的最接近的 Vala 代码是:

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;
}

我不确定编译器是否理解这里的括号,它可能认为我想在这里声明一个拥有的字符串的无主数组...

更新:原来问题是类型推断总是创建一个拥有的变量(见nemequs评论)。

甚至还有一个bug report for this.

所以这很好用(repeat 函数中没有字符串重复):

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;
}

在精灵中会是这样的:

[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

Genie 代码存在无法编译的额外问题,因为解析器无法推断出 array of.

之后的内容

这似乎与我在 中遇到的问题类似。

我有 reported this a Genie bug.