Does D have a sufficiently expressive type system to make it feasible to work dynamically?

StackOverflow https://stackoverflow.com/questions/9732241

  •  24-05-2021
  •  | 
  •  

문제

Does D have a sufficiently expressive type system to make it feasible to work dynamically (that is, with multiple classes of values) within a statically typed framework?

I ask, after reading Dynamic languages are static languages. Sample code, if any, is highly appreciated.

도움이 되었습니까?

해결책

If you only use std.variant.Variant then D is essentially a dynamically typed language. Here's an example of its usage from the library reference page:

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
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top