Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strings passed to a function not altered by it in the D Language

Tags:

d

I am a long time C programmer. I have heard about D and have decided to learn it. I like the capabilities it seems to offer. I have come across an issue that has me stumped. I have looked online and haven't found much of an answer. I am trying to pass strings through a function:

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

The output is as follow:

t1 = Hello t2 = there
s1 = Hello s2 = there
a1 =  a2 = 

I have tried to search online for an answer can I can't find one. I suspect that I am just not asking the right question. I know I can do this using char strings, but I am trying to do this the "D way". Will somebody point me to a reference that can help with this or tell me the question to ask?

If this has been answered before, I apologize. I probably didn't ask the correct question.

Thank you in advance for your time.

Michael

like image 895
Michael S. Avatar asked Nov 29 '25 01:11

Michael S.


1 Answers

Add ref to your parameters (e.g., int foobar(ref string s1, ref string s2)). A string is just regular slice to immutable chars so it gets passed around by value. If you want to change the slices they needs to be passed by reference.

like image 188
eco Avatar answered Dec 02 '25 05:12

eco



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!