d , Can't define an associative array type: opEquals doesn't exist

Can't define an associative array type: opEquals doesn't exist


Tag: d

I can't use non-primitive types as keys for associative arrays; attempting to do so will result in the following error on the line where I define the AA:

Error: AA key type MyString does not have 'bool opEquals(ref const MyString) const

I first discovered this when using the type CollisionHandler[Tuple!(TypeInfo, TypeInfo)] where CollisionHandler is an alias for a function pointer type.

However, even the example code from the "Using Structs or Unions as the KeyType" heading under the Associative array documentation page fails with the same error:

import std.string;

struct MyString
    string str;

    size_t toHash() const @safe pure nothrow
        size_t hash;
        foreach (char c; str)
        hash = (hash * 9) + c;
        return hash;
    // opEquals defined here?
    bool opEquals(ref const MyString s) const @safe pure nothrow
        return std.string.cmp(this.str, s.str) == 0;

int[MyString] foo; // errors here

void main() {


Here, MyString.opEquals is defined and should have the proper signature, yet the dmd compiler says that it isn't implemented. The fact that this snippet comes straight from the docs makes me suspect it's a compiler bug, but maybe I'm just missing something?

Running DMD under Linux, but the issue also happens under Windows 7. DMD version:

$ dmd --help
DMD64 D Compiler v2.066.1
Copyright (c) 1999-2014 by Digital Mars written by Walter Bright
Documentation: http://dlang.org/


This is a case of a misleading error message emitted by the compiler.

The problem is with the @safe annotation on the opEquals method. In 2.066.1, std.string.cmp is not @safe - however, the compiler displays the wrong error message. If you rename opEquals to something else, e.g. foo, you'll get a different error message:

test.d(19): Error: safe function 'test.MyString.foo' cannot call system function
'std.algorithm.cmp!("a < b", string, string).cmp'

The workaround is to remove @safe, or replace it with @trusted.

Note that this problem does not manifest in the development version of DMD, so it should be fixed in 2.067.0.


ZipArchive with embedded ZIP concated to EXE

In my gaming project, I implemented embedded ZIP resource file with the method described here in the second answer (using blob.S to embed & mark the ZIP): Is there any standard way of embedding resources into Linux executable image? In long run, I would like to simplify build process and...

What does it mean that the D garbage collector is “not guaranteed to run the destructor for all unreferenced objects”?

The D documentation at http://dlang.org/class.html#destructors states that "The garbage collector is not guaranteed to run the destructor for all unreferenced objects." However I am a little contused as to what this actually means. Is this saying that a GC implementation can choose to not call destructors when it collects the...

Mechanics behind adding two arrays in D language

I am a bit curious mechanics behind code below: int[3] a1 = [ 1 , 2 , 3 ]; int[3] a2 = [ 1 , 2 , 3 ]; int[3] result = a1[] + a2[]; foreach (i; result) writeln(i); Result is 2,4,6 . In C++ we had to overload '+'...

D: byLine with remove (http) file?

I need to split remote file byLine with D. http://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/2.5_day.csv The examples show only how to work with files on FS. But can I work with remote files?...

How to intersect to array in D?

I need to find difference between two arrays of strings in D. The problem, that I can't understand how to use SetDifference from std.algorithm. auto x = SetDifference(filearr1,filearr2); get error: Error: struct std.algorithm.SetDifference cannot deduce function from argument types !()(string[], string[]), candidates are:...

GetWindowLongPtr in D on Windows?

I was unable to find 'GetWindowLongPtr' in standard D's modules. So I went to MSDN ( https://msdn.microsoft.com/ru-ru/library/windows/desktop/ms633585(v=vs.85).aspx ). Attached the lib: pragma (lib, "user32.lib"); Declared a function: extern (Windows) { export LONG_PTR GetWindowLongPtrA(in HWND hWnd, in int nIndex); } But the compiler (dmd) says: [email protected] This scheme worked for AppendMenu...

How to use libgit's git_repository_open in d

I am trying to use the libgit2 library in d. I always get a segmentation fault upon the the program's exit. The error does not happen before the exit, when I open and close the repository. It would seem that this is an issue with the garbage collector, but manually...

Intercompatibility between std.stdio.File and std.stream.*

Is there any good way to turn a std.stdio.File into something that is an instance of a stream from std.stream? Reason: I find myself wanting a generic logging utility working on streams, and I want to pass it std.stdio.stderr which is a std.stdio.File....

Floating point maxing out loop doesn't terminate in D, works in C++

I have two similar programs one in C++ and another in D. The compilation is on on Windows7 64bit, to 64bit binaries. C++ version, VS 2013: #include <iostream> #include <string> int main(int argc, char* argv[]) { float eps = 1.0f; float f = 0.0f; while (f + eps != f)...

Why is my D code to sum a vector up x4 slower than C?

I was wondering why D code is so slow? I originally used std.algorithm.sum but the performance was even worse. My D code: import std.algorithm; import std.stdio; void main() { immutable int n = 10000000; int[] v = new int[n]; fill(v,1); int total = 0; foreach (int i; 0 .. n)...

Right way to do “const pointer to non-const” in D?

Ok, according to http://dlang.org/const-faq.html#head-const there is no way to have a const pointer to non-const in D. But there is a good practice: declare a field in a class const and compiler let you know if you forget to initialize it. Is there any way to protect myself from forgetting...

Split a DNA sequence into a list of codons with D

DNA strings consist of an alphabet of four characters, A,C,G, and T Given a string, ATGTTTAAA I would like to split it in to its constituent codons ATG TTT AAA codons = ["ATG","TTT","AAA"] codons encode proteins and they are redundant (http://en.wikipedia.org/wiki/DNA_codon_table) I have a DNA string in D and would...

Cannot Build/Run VisualD Console Example

I installed Visual D a few minutes ago(I wanted to give the language a test drive) and, using the built-in console example, tried to build and run it. Here is the code that Visual Studio generated for me: import std.stdio; int main(string[] argv) { writeln("Hello D-World!"); return 0; } And...

Function namespacing issues in D

Say I have a class Foo with a member function bar(). I also have a completely unrelated function which happens to be named bar() as well. class Foo { /* ... */ void bar() { /* ... */ } } void bar() { /* ... */ } It seems that...

How to get array's element type size in D?

Say, I have an array: int[] a = ... And I want to get size of its element. I can do something like this: a.sizeof / a.length, but it looks a bit complex and I think there is a way to do something like this: ArrayLementType!(a).sizeof. How does "ArrayLementType" looks...

How to check if command is exists?

I need to detect if app is present in system. I use for it std.process the next code is trow exception if executable command do not exists: try { auto ls = execute(["fooapp"]); if (ls.status == 0) writeln("fooapp is Exists!\n"); } catch (Exception e) { writeln("exception"); } Is there any...

In D, how can I declare a hash of immutable types that is itself mutable?

I believe I was able to do this in an earlier version of the language, and indeed, code I wrote several months ago, which compiled fine then, does not compile now. Example: immutable(X)[int] myhash; myhash[5] = some_immutable_X; //previously fine. myhash[5] = some_other_immutable_X; //previously fine also. Now however, dmd complains with...

DUB: How to specify version of git repo?

I use DUB, and want to include ncurses to project https://github.com/D-Programming-Deimos/ncurses/ it have not explicitly version specification on github page. But during build DUB ask me to specify version explicitly: WARNING: A deprecated branch based version specification is used for the dependency ncurses. Please use numbered versions instead. How I...

Dlang generics for classes

first time poster. I've been using Java for a few years now, and have decided to learn D. In Java, you can declare a class with a generic type, and create a new object from that class. Like: public class foo<T> { public foo() { ... } } and then...

Formatting a string in D

I read on D's documentation that it's possible to format strings with arguments as print statements, such as the following: float x = 100 / 3.0; writefln("Number: %.*g", 2, x); Number: 33.33 However, I'm wondering how I would do this if I just wanted the string equivalent, without printing it....

Should std.algorithm.find demand a reference to range elements?

I have been working on a class-based finite random access range. When performing a few tests on it: auto myRange = /* construct my range */ static assert (isRandomAccessRange!(typeof(myRange))); // static assert (!isInfinite!(typeof(myRange))); // both pass auto preamble = myRange[0..128]; assert( all!"a == 0"(preamble)); // check for all zeros I...

Iterating through files in a folder in D

In D programming, how can I iterate through all files in a folder? Is there a D counterpart to python's glob.iglob?

Faulty D Dependency Logic in SCons

I've tracked down a bug in the dependency logic for D sources in SCons. The self.cre regexp import\s+(?:\[a-zA-Z0-9_.\]+)\s*(?:,\s*(?:\[a-zA-Z0-9_.\]+)\s*)*; in SCons.Scanner.D doesn't cover patterns such as... import IMPORT_PATH : SYMBOL; ...only: import IMPORT_PATH; Same with the self.cre2 regexp (?:import\s)?\s*([a-zA-Z0-9_.]+)\s*(?:,|;) two lines later. I believe both the self.cre and self.cre2 regexps need...

Split string on un-escaped character in D

What is the best way to split a string on an un-escaped character? Eg. split this (raw) string `example string\! it is!split in two parts` on '!', so that it produces this array: ["example string! it is", "split in two parts"] std.regex.split seems to almost be the right thing. There...

How to add icon in D application?

I want to add icon to exe file of my application? How can I do it. I would like it's added automatically when I build my app with dub.

How to fix D “memory leaks”

So I've been searching for a solution to this problem for some time. I've written a program to take data from two separate text files, parse it, and output to another text file and an ARFF file for analysis by Weka. The problem I'm running into is that the function...

Byte InputRange from file

How to construct easily a raw byte-by-byte InputRange/ForwardRange/RandomAccessRange from a file?

Can't connect to MySQL/MariaDB database from vibed app

All work fine if I use custom main ( void main() instead of shared static this() ). With default main I am getting "Access Violation" error. It's look like MySQL not allow connecting to it from localhost, but in my.ini I added string: bind-address = code, if it's help:...

TUI (text user interface) for D?

I would like to write a console app with text UI in D. I looked at curses, but it seems that it works only on unix. Are there any cross-patform alternatives?

D lang record separator is being lost after string cast

I am new to D please forgive the terrible code below. I am opening a .gz file and reading it chunk by chunk for uncompressing it. The data in the uncompressed file is like : aRSbRScRSd, There are record separators(ASCII code 30) between each record(records in my dummy example a,b,c)....

Array of Key->Value array

I am starting with the D language (D2) and I am trying to do the following: string[int] slice1 = [ 0:"zero", 1:"one", 2:"two", 3:"three", 4:"four" ]; string[int] slice2 = [ 0:"zero", 1:"one", 2:"two"]; alias MySlice = string[int]; MySlice[] list; list[] =slice1; list[]=slice2; writeln(list); It compiles but the list stays empty....

Error in Defining an associative array in D

So I would like to implement a hash lookup for translating codons to amino acids in D. When i write int[string] codon_table = [ "ATG": 'M', "TTT": 'F', "TTC": 'F', "TTA": 'L', "TTG": 'L', "CTT": 'L', "CTC": 'L', "CTA": 'L', "CTG": 'L', "ATT": 'I', "ATC": 'I', "ATA": 'I', "GTT": 'V',...

How do i construct string from byte array in D

I have array of bytes wich is defined as pointer + size: size_t size; // size in bytes void *data; // NOT zero-terminated string How do I construct, preferrably zero-copy, 'string' from it? ...

D Language Static Class Function Undefined Identifier

I started learning the D programming language(it's pretty awesome), and ran into a slight problem when I started to explore functions. The setup is pretty basic; it's just a way to figure out the similarities of the language to others that I have used. Here is my class declaration: module...

Pure constructors in class templates

I have some code that works, and I'm not sure why. I'm instantiating a class as an immutable variable. There are no immutable constructors in the class and none are labeled as pure, but it just works anyway. I also read that pure constructors can be used across the board...

Mixin's names parameterization with template argument

Is it possible to generate a name for a function within a mixin template? Something like this: mixin template Generator(string name) { @property void mixin(name) pure nothrow // mixin(name) is not valid :( { //some cool stuff here } } ...

D, setting class property, no identifier for declarator

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: [email protected]:~/Sail/source# dmd nonsense.d nonsense.d(8): Error: no identifier for declarator b.name nonsense.d(8): Error: Declaration expected, not '='...

D: Converting DateTime to Date: cannot cast from DateTime to Date

I need to convert DateTime type to Date. here is my code: DateTime dt = DateTime(2015, 1, 1, 14, 10, 13); Date z = cast(Date)dt; Error: cannot cast from DateTime to Date Whats wrong?...

Dlang chomp() not working on certain delimiters

The statement writefln("%s", chomp("Hello world", "orld")) produces the correct output Hello w. However, the delimiters ":" and "," don't get chomped. writefln("%s", chomp("Hello : world", ":")) outputs Hello : world The docs for std.string.chomp don't mention anything about reserved chars, unless I'm misunderstanding something. Is this a bug or working...

(dlang, GtkD) Using menubar

I copied the code in this site(https://sites.google.com/site/gtkdtutorial/#chapter2_2) and compiled it by dmd2. import gtk.MainWindow; import gtk.Box; import gtk.Main; import gtk.Menu; import gtk.MenuBar; import gtk.MenuItem; import gtk.Widget; import gdk.Event; void main(string[] args) { Main.init(args); MainWindow win = new MainWindow("MenuBar Example"); win.setDefaultSize(250, 200); MenuBar menuBar = new MenuBar(); menuBar.append(new FileMenuItem()); Box box...

Is it safe to cast between B* and D* if D contains an object of type B as its first member?

Consider the following: struct B { int x; } struct D { B b; int y; } void main() { auto b = cast(B*) new D(); writeln(b.x == b.x); auto d = cast(D*) b; writeln(b.x == d.b.x); } Is this program guaranteed to write "true" twice? I couldn't find these...

How to convert array of strings to string in D?

I have got array of strings like: string [] foo = ["zxc", "asd", "qwe"]; I need to create string from them. Like: "zxc", "asd", "qwe" (yes every elements need be quoted and separate with comma from another, but it should be string, but not array of strings. How can I...

Is it's possible make GUI and console app in one exe?

I want to develop App with GUI, that can be run without showing GUI. How I can do it? If it's possible would this App work on servers that do not have nothing related with GUI (ex: can I work with such App with ssh or so). Any example please...

D lang appending to multidimensional dynamic array

I want to append a 2D array to my 3D array. I expect it should be same as int[] arr; arr ~= 3; void readInput() { char[][][] candidate; char[] buff; size_t counter = 0; while ( stdin.readln(buff) ) { char[][] line = buff.chomp().split(); writeln(line); candidate ~= line; writeln(candidate); if (++counter...