如何返回所有指向内存中相同位置的无主字符串的数组?
示例:
init
var str = "ABC"
var unowned_string_array = repeat (str, 5)
def repeat (s: string, n: int): array of string
// code
并且此数组将包含5个元素(相同的字符串“ABC”),都指向相同的位置
答案 0 :(得分:2)
我能得到的最接近的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评论)。
所以这很好用(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;
}
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
由于解析器无法推断出array of
之后的内容,因此Genie代码还存在无法编译的问题。
这似乎与我nested generic types已有的问题类似。