...ing logging 4.0

はてなブログに移行しました。D言語の話とかいろいろ。

Final / Invariant / Const

ふむふむ.

import std.stdio;

void main()
{
    // Note: type of "string literal".dup is char[]
    {
        // char[] s = "hoge"; // error, invariant(char)[] to char[]
        char[] s = "hoge".dup;
        s[0] = 'H';
        s = "HOGE".dup;
        writefln(s);
    }
    // Note: type of string literal is invariant(char)[]
    {
        invariant(char)[] s = "hoge";
        //s[0] = 'H'; // error, not mutable
        s = "HOGE";
        writefln(s);
    }
    // Note: alias const(char)[] string;
    {
        string s = "hoge";
        //s[0] = 'H'; // error, not mutable
        s = "HOGE";
        writefln(s);
    }
    // Note: dup is variant, idup is invariant
    {
        const(char)[] s = "hoge";      // ok, invariant(char)[] to const(char)[]
        //invariant(char)[] a = s;     // error, const(char)[] to invariant(char)[]
        //invariant(char)[] a = s.dup; // error, char[] to invariant(char)[]
        invariant(char)[] b = s.idup;
    }
    {
        final char[] s = "hoge".dup;
        s[0] = 'H';
        // s = "the world!".dup; // error, final
        writefln(s);
    }
    // Note: do not change "string literal"
    {
        char[] s = cast(char[])"hoge";
        //s[0] = 'H'; // undefined operation
    }
    char[] line = readln();
}