FAQFAQ   SearchSearch   MemberlistMemberlist   UsergroupsUsergroups   RegisterRegister 
 ProfileProfile   Log in to check your private messagesLog in to check your private messages   Log inLog in 

How to initialize associative arrays?

 
Post new topic   Reply to topic     Forum Index -> General
View previous topic :: View next topic  
Author Message
dcoder



Joined: 04 May 2010
Posts: 5

PostPosted: Thu Jun 10, 2010 11:27 am    Post subject: How to initialize associative arrays? Reply with quote

Hello. Still going through the tutorials.

The following program does not work:

Code:

import std.stdio;
import std.string;

static string greetings[string] =
  [ "Klaus":"Guten Tag", "Dave":"Hello",
    "Maria":"ibuenas tardes", "Antoine":"Bon Jour" ];


void main() {
  foreach( string name, string msg; greetings) {
    writefln( "%s: %s!", name, msg);
  }
  return;
}


Here's the error:


$ dmd Greetings.d
Greetings.d(5): Error: non-constant expression ["Klaus":"Guten Tag","Dave":"Hello","Maria":"ibuenas tardes","Antoine":"Bon Jour"]


Well, I don't understand why the compiler considers the initialization list non-constant. What is varying?

So poking around the internet, it seems like I need to declare my greetings assoc array as static, but that didn't work.

And, then perhaps I need to throw some const in there:

Code:

import std.stdio;
import std.string;

const string greetings[const string] =
  [ "Klaus":"Guten Tag", "Dave":"Hello",
    "Maria":"ibuenas tardes", "Antoine":"Bon Jour" ];


void main() {
  foreach( const string name, const string msg; greetings) {
    writefln( "%s: %s!", name, msg);
  }
  return;
}


$ dmd Greetings.d
Greetings.d(5): Error: non-constant expression ["Klaus":"Guten Tag","Dave":"Hello","Maria":"ibuenas tardes","Antoine":"Bon Jour"]
Internal error: e2ir.c 4600





Aside from my ignorance, what is going on here? How can I fix this?

thanks.
Back to top
View user's profile Send private message
torhu



Joined: 30 Mar 2006
Posts: 56

PostPosted: Sat Jun 26, 2010 11:51 am    Post subject: Reply with quote

Unfortunately, assoc array initializers can't be used in static initialization. You have to put them inside a function.
Back to top
View user's profile Send private message
Display posts from previous:   
Post new topic   Reply to topic     Forum Index -> General All times are GMT - 6 Hours
Page 1 of 1

 
Jump to:  
You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot vote in polls in this forum


Powered by phpBB © 2001, 2005 phpBB Group