On Wednesday, 30 September 2015 at 17:51:50 UTC, Jan Johansson
wrote:
Hello all,
I'm testing D language, and the first thing I want to do is to
separate declaration from implementation. I was happy to find
support of interfaces in the D language, and set out to do a
basic test. However, this test failed, and I want some newbie
help to understand how it should be done in D language.
----------------------
The interface file (I called it test.di):
// Interface
interface IMyTest {
void Write(string message);
}
// Factory for type implementing IMyTest
IMyTest createInstance();
----------------------
The library file (I called it test.d):
import std.stdio;
class MyTest : IMyTest {
void Write(string message) {
writeln(message);
}
}
IMyTest createInstance() {
return new MyTest;
}
----------------------
And finally the main file (I called it main.d):
import test;
import std.stdio;
void main() {
auto p = createInstance();
p.Write("Hello, World!");
}
----------------------
The assumption was that I could do:
dmd test.d test.di -lib -oftest
and next do:
dmd main.d test.di test.a
The shared information is in the test.di file.
However, this failed, since the first statement generates the
following:
dmd test.d test.di -lib -oftest
Error: module test from file test.di conflicts with another
module test from file test.d
I guess it is because the file name test.d and test.di creates
conflict, surfaced as module test.
How can I accomplish what I want to do?
Kind regards,
Jan Johansson
Like Adam said, the real difference between a .d and a .di file
is that the .di file has all the guts removed and is just the
declarations.
If using a .di file is really what you want, you could try
something like this?
test.d:
module test;
interface IMyTest {
void Write(string message);
}
IMyTest createInstance() {
class MyTest : IMyTest {
void Write(string message) {
import std.stdio;
writeln(message);
}
}
return new MyTest;
}
---------------
test.di:
module test;
interface IMyTest {
void Write(string message);
}
IMyTest createInstance();
---------------
main.d:
import test;
void main() {
auto p = createInstance();
p.Write("Hello, World!");
}
--------------
and then
dmd test.d -lib -oftest
and
dmd main.d test.di test.a
Also like Adam said, dmd can create these .di files for you so
you don't have to!
(This is untested, but should work/be close to working)