在 D 语言中传递给函数的字符串没有被它改变
Strings passed to a function not altered by it in the D Language
我是一名资深的 C 程序员。我听说过 D 并决定学习它。我喜欢它似乎提供的功能。我遇到了一个让我难过的问题。我在网上看过,但没有找到太多答案。我正在尝试通过函数传递字符串:
module main;
import std.stdio;
import std.string;
int foobar(string s1, string s2)
{
string t1="Hello";
string t2="there";
writeln("t1 = ",t1, " t2 = ", t2);
s1=t1;
s2=t2;
writeln("s1 = ",s1," s2 = ",s2);
return 0;
}
int main(string[] args)
{
string a1;
string a2;
foobar(a1, a2);
writeln("a1 = ",a1," a2 = ",a2);
return 0;
}
输出结果如下:
t1 = Hello t2 = there
s1 = Hello s2 = there
a1 = a2 =
我已经尝试在网上搜索答案,但找不到。我怀疑我只是没有问正确的问题。我知道我可以使用 char 字符串来做到这一点,但我正在尝试 "D way" 来做到这一点。有人会指出可以帮助解决这个问题的参考资料或告诉我要问的问题吗?
如果之前有人回答过这个问题,我深表歉意。我可能没有问正确的问题。
提前感谢您的宝贵时间。
迈克尔
将 ref
添加到您的参数中(例如,int foobar(ref string s1, ref string s2)
)。字符串只是不可变字符的常规切片,因此它按值传递。如果要更改切片,则需要通过引用传递它们。
我是一名资深的 C 程序员。我听说过 D 并决定学习它。我喜欢它似乎提供的功能。我遇到了一个让我难过的问题。我在网上看过,但没有找到太多答案。我正在尝试通过函数传递字符串:
module main;
import std.stdio;
import std.string;
int foobar(string s1, string s2)
{
string t1="Hello";
string t2="there";
writeln("t1 = ",t1, " t2 = ", t2);
s1=t1;
s2=t2;
writeln("s1 = ",s1," s2 = ",s2);
return 0;
}
int main(string[] args)
{
string a1;
string a2;
foobar(a1, a2);
writeln("a1 = ",a1," a2 = ",a2);
return 0;
}
输出结果如下:
t1 = Hello t2 = there
s1 = Hello s2 = there
a1 = a2 =
我已经尝试在网上搜索答案,但找不到。我怀疑我只是没有问正确的问题。我知道我可以使用 char 字符串来做到这一点,但我正在尝试 "D way" 来做到这一点。有人会指出可以帮助解决这个问题的参考资料或告诉我要问的问题吗?
如果之前有人回答过这个问题,我深表歉意。我可能没有问正确的问题。
提前感谢您的宝贵时间。
迈克尔
将 ref
添加到您的参数中(例如,int foobar(ref string s1, ref string s2)
)。字符串只是不可变字符的常规切片,因此它按值传递。如果要更改切片,则需要通过引用传递它们。