Skip to content

Commit 710f08e

Browse files
committed
better array value and ref semantics explanation
1 parent f37c1b3 commit 710f08e

1 file changed

Lines changed: 24 additions & 8 deletions

File tree

content/posts/jai-guide.md

Lines changed: 24 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -344,14 +344,6 @@ you can get the memory adress of the first element in an array using the `array.
344344

345345
Both Static Arrays and Dynamic Arrays are autocasted to Array Views if the array view is a parameter. Because strings are array views with u8, both share the same definition.
346346

347-
Arrays in jai are simply a tiny struct that holds the size and location of where the array actually is in memory. so copying an array directly makes an array that points to the same data.
348-
349-
You can initialize arrays using the following syntax:
350-
351-
```jai
352-
array: [4]float = float.[10.0, 20.0, 1.4, 10.0];
353-
```
354-
355347
regular arrays:
356348
```jai
357349
// simple array
@@ -403,6 +395,30 @@ array: [2][2]int = .[.[1, 0], .[0, 3]]; // initializing a 2D array with inferred
403395
value: int = array[0][0]; // indexing a 2D array
404396
```
405397

398+
Static arrays actually hold all of their own data, meaning that copying a static array does a full copy.
399+
Dynamic arrays and array views (slices) are basically just pointers,
400+
therefore copying them doesnt copy the actual data, therefore they act like reference types.
401+
This is what each type of array basically is in practice:
402+
403+
```jai
404+
// regular array
405+
one largu unit holding all of the actual data
406+
407+
// dynamic array
408+
struct {
409+
count: s64; // number of elements
410+
data: *void; // location of the first element
411+
allocated: s64; // total bytes used
412+
allocator: Allocator; // the allocator in use
413+
}
414+
415+
// array view (slice)
416+
struct {
417+
count: s64; // number of elements
418+
data: *u8; // location of the first element
419+
}
420+
```
421+
406422
## Polymorphism (Generics)
407423

408424
In jai generics is called polymorphism.

0 commit comments

Comments
 (0)