Language Reference

IchorDev zxinsworld at gmail.com
Tue Aug 20 04:53:16 UTC 2024


On Monday, 19 August 2024 at 06:47:10 UTC, Ron Tarrant wrote:
> On Saturday, 17 August 2024 at 22:17:59 UTC, Pete wrote:
>> I'm starting to learn the D language and started reading the 
>> Language Reference.
>
> I've never read the reference, but I can tell you that [**The 
> Book**](https://ddili.org/ders/d.en/index.html) (over-hyped or 
> not) gives you a solid grounding. It's the only D 
> reference/tutorial that's kept more-or-less up-to-date (I say 
> at the risk of excessive hyphenation). You may or may not find 
> it slow going, depending on your taste, but at this point, it's 
> the best we have for getting in there are getting your feet wet.
>
> If you're new to computer science, it covers basics I first 
> learned back in the mid-1980's, the kind of stuff rarely 
> mentioned these days that lends one a solid understanding of 
> these machines we all love to tinker with.

If you like to stay on the bleeding edge then it’s… certainly out 
of date.

The book also says slices are reference types, which is 
completely erroneous. Where associative array or class variables 
are simply a pointer that is not semantically treated as one 
(i.e. no dereferencing is required), slices are more complicated.
Here’s the book’s example of a value type:
```d
void reduceEnergy(double energy) {
     energy /= 4;
}
```
As you can see, since we only modified a value type—even though 
its new value was derived from the old one—nothing happens and 
this function is actually useless. Now, let’s see their deceptive 
presentation of slices as reference types:
```d
void makeFirstLetterDot(dchar[] str) {
     str[0] = '.';
}
```
Oh, see? It’s totally a reference type, because this modifies the 
same data as at the caller site. But hang on, by that logic 
*this* is also a ‘reference type’:
```d
struct DCharArray{
   dchar* ptr;
   size_t length;
}
void makeFirstLetterDot(DCharArray str){
     str[0] = '.';
}
```
What the book misses is the proper explanation that despite 
*containing* a pointer—which is a reference by its very 
nature—slices are still value types because they also incorporate 
a length, which is copied:
```d
void reduceLength(dchar[] str){
     str = str[0..$-1];
}
```
This does nothing, because we modified the slice’s length, and 
the slice’s length is copied rather than referenced. Notice that 
the pointer remains the same, which distinguishes this from the 
behaviour of reassigning to an associative array or class 
variable; wherein a new instance will be distinct from the old 
one, and writing to its value fields will not directly affect the 
old instance.


More information about the Digitalmars-d mailing list