gpt4 book ai didi

D 是否有足够表达的类型系统使其动态工作可行?

转载 作者:行者123 更新时间:2023-12-04 03:16:26 25 4
gpt4 key购买 nike

D 是否有一个足够表达的类型系统,使其能够在静态类型框架内动态工作(即,使用多个类的值)?

我问,看完Dynamic languages are static languages.非常感谢示例代码(如果有)。

最佳答案

如果您只使用 std.variant.Variant 那么 D 本质上是一种动态类型语言。以下是库引用页面中的使用示例:

Variant a; // Must assign before use, otherwise exception ensues

// Initialize with an integer; make the type int
Variant b = 42;
assert(b.type == typeid(int));

// Peek at the value
assert(b.peek!(int) !is null && *b.peek!(int) == 42);

// Automatically convert per language rules
auto x = b.get!(real);

// Assign any other type, including other variants
a = b;
a = 3.14;
assert(a.type == typeid(double));

// Implicit conversions work just as with built-in types
assert(a > b);

// Check for convertibility
assert(!a.convertsTo!(int)); // double not convertible to int

// Strings and all other arrays are supported
a = "now I'm a string";
assert(a == "now I'm a string");
a = new int[42]; // can also assign arrays
assert(a.length == 42);
a[5] = 7;
assert(a[5] == 7);

// Can also assign class values
class Foo {}
auto foo = new Foo;
a = foo;
assert(*a.peek!(Foo) == foo); // and full type information is preserved

关于D 是否有足够表达的类型系统使其动态工作可行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9732241/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com