如何使用类型推断以便删除可能的 immutable/const?
How to use type inference so that possible immutable/const is removed?
如何使用类型推断来删除变量声明中的 immutable/const?这可能吗?
immutable uint immutableX = 42;
// keep the type (uint) but remove the immutability
/* compiler magic */ mutableX = immutableX;
非类型推断方案为:
uint mutableX = immutableX;
完整示例:
void main()
{
immutable uint immutableX = 42;
pragma(msg, "immutableX: ", typeof(immutableX));
assert(typeof(immutableX).stringof == "immutable(uint)");
// how to use type inference so that possible immutable/const is removed ?
// the expected type of mutableX is uint
auto mutableX = immutableX;
pragma(msg, "mutableX: ", typeof(immutableX));
// this should be true
assert(typeof(immutableX).stringof == "uint");
}
根据用例,有 std.traits.Unqual
,它删除了最外层的 immutable
、const
、shared
等:
import std.traits : Unqual;
immutable int a = 3;
Unqual!(typeof(a)) b = a;
static assert(is(typeof(b) == int));
一个更简单的解决方案可能是 cast()
:
immutable int a = 3;
auto b = cast()a;
static assert(is(typeof(b) == int));
哪个正确取决于您将在何处以及如何使用它。
如何使用类型推断来删除变量声明中的 immutable/const?这可能吗?
immutable uint immutableX = 42;
// keep the type (uint) but remove the immutability
/* compiler magic */ mutableX = immutableX;
非类型推断方案为:
uint mutableX = immutableX;
完整示例:
void main()
{
immutable uint immutableX = 42;
pragma(msg, "immutableX: ", typeof(immutableX));
assert(typeof(immutableX).stringof == "immutable(uint)");
// how to use type inference so that possible immutable/const is removed ?
// the expected type of mutableX is uint
auto mutableX = immutableX;
pragma(msg, "mutableX: ", typeof(immutableX));
// this should be true
assert(typeof(immutableX).stringof == "uint");
}
根据用例,有 std.traits.Unqual
,它删除了最外层的 immutable
、const
、shared
等:
import std.traits : Unqual;
immutable int a = 3;
Unqual!(typeof(a)) b = a;
static assert(is(typeof(b) == int));
一个更简单的解决方案可能是 cast()
:
immutable int a = 3;
auto b = cast()a;
static assert(is(typeof(b) == int));
哪个正确取决于您将在何处以及如何使用它。