在 D 中使用枚举字符串比使用字符串有什么优势?

What's the advantage of using enum string over string in D?

D中的

enum可以作为常量使用:

import std.stdio;

void main()
{
    enum secondsPerDay = 60 * 60 * 24;
    // enum int secondsPerDay = 60 * 60 * 24;
    writeln(secondsPerDay * 1024);

    enum fileName = "list.txt";
    writeln(fileName, typeof(fileName).stringof);

    auto fileName2 = "list.txt";
    writeln(fileName2, typeof(fileName2).stringof);
}

那么,当字符串无论如何都不可变时,使用 enum 比 auto (string) 有什么优势?这些是返回的结果。

88473600
list.txtstring
list.txtstring

与字符串没有太大区别。不过,一般来说,不可变和枚举之间的区别在于枚举总是在编译时求值。不可变值仅在编译时在静态上下文中评估。

另一个区别是枚举有点像 copy/pasted 使用站点。观察:

enum array = [1,2,3];
void main() {
      auto arr = array; // this actually allocates a new array [1,2,3]
      static immutable arr2 = array; // this doesn't
}

真正的区别是 static 而不是 immutable,它将数据放在静态数据段中,但它仍然与仅创建编译时的 enum 形成对比值。

无论如何,对于普通字符串,这没有区别。 enum 在函数结果或可变数组上使用它时发挥更多作用,其中编译时位可能意味着在运行时删除函数调用,或者 "pasted constant" 位可能意味着添加分配在运行时。

这是 immutable(char)[](又名字符串)和 immutable(char[])(枚举字符串)之间的区别:

void main() 
{ 
   string s = "string1";
   enum e = "enum1";

   s = e; // allowed
   e = s; // error
}

来自此处找到的文档:http://dlang.org/enum.html

清单常量

如果匿名枚举只有一个成员,{}可以省略:

enum i = 4;      // i is 4 of type int
enum long l = 3; // l is 3 of type long

这样的声明不是左值,这意味着它们的地址不能被获取。它们只存在于编译器的内存中。

enum size = __traits(classInstanceSize, Foo);  // evaluated at compile-time

使用清单常量是一种惯用的 D 方法,用于强制对表达式进行编译时计算。