字符串传递给D语言中未被其更改的函数

Mic*_* S. 3 d

我是一名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;
}
Run Code Online (Sandbox Code Playgroud)

输出如下:

t1 = Hello t2 = there
s1 = Hello s2 = there
a1 =  a2 = 
Run Code Online (Sandbox Code Playgroud)

我试图在网上搜索一个答案,我找不到一个.我怀疑我不是在问正确的问题.我知道我可以使用char字符串来做到这一点,但我试图用"D方式"来做这件事.有人会给我一个可以帮助解决这个问题的参考资料,或者告诉我要问的问题吗?

如果之前已经回答过,我道歉.我可能没有问正确的问题.

提前谢谢您的时间.

迈克尔

eco*_*eco 6

添加ref到您的参数(例如int foobar(ref string s1, ref string s2)).字符串只是对不可变字符的常规切片,因此它会按值传递.如果要更改切片,则需要通过引用传递它们.