2

I'm just getting started with D and this is completely strange. Here's my code:

class User
{
    int id;
    string name;
}

User b = new User();
b.name = "Edwin";

And here's my error:

root@d-testing:~/Sail/source# dmd nonsense.d 
nonsense.d(8): Error: no identifier for declarator b.name
nonsense.d(8): Error: Declaration expected, not '='

What the heck am I doing wrong here? Every class example I've seen does it this way.

RandomInsano
  • 1,204
  • 2
  • 16
  • 36
  • It is a good question actually, because many people use(d) languages where arbitrary statements may appear anywhere in the file. This is especially true with scripting languages. – DejanLekic Mar 11 '15 at 11:10
  • This is absolutely hilarious to me since I use C and C# a lot. For some silly reason because some of the examples I saw didn't define any function, it didn't click. Too much Python lately :D – RandomInsano Mar 12 '15 at 01:52
  • Python was the first language that came to my mind when I saw your comment. :) – DejanLekic Mar 12 '15 at 11:54

1 Answers1

8

You can't execute code directly in the root of the file like that in D. You are allowed to declare new variables, such as the 'User b = new User()' (though it may not do what you expect), but not execute arbitrary statements like adjusting b.name.

You need to wrap the code you want to execute in a main() method, such as:

void main() {
    User b = new User();
    b.name = "Edwin";
}
Abstract type
  • 1,901
  • 2
  • 15
  • 26
Kapps
  • 328
  • 1
  • 3