Skip to content

Commit fc0e57b

Browse files
committed
update to generics
1 parent dfc5ccd commit fc0e57b

1 file changed

Lines changed: 18 additions & 8 deletions

File tree

content/posts/jai-guide.md

Lines changed: 18 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -405,9 +405,9 @@ Instead, an array has a `.data` field for its backing pointer.
405405

406406
In jai generics is called polymorphism.
407407

408-
Jai’s generics are compile-time polymorphism using `$T` and `Type` parameters.
408+
Jai’s generics are compile-time polymorphism using the `x: $T` and `T: Type` parameters.
409409

410-
Generic function:
410+
Generic function taking variable of any type:
411411
```jai
412412
foo :: (x: $T) {
413413
print("%\n", x);
@@ -417,22 +417,32 @@ foo(1);
417417
foo("hello");
418418
```
419419

420+
Generic function taking a type itself as parameter:
421+
```jai
422+
foo :: (T: Type) {
423+
print("size of type = %", size_of(T));
424+
}
425+
426+
foo(int);
427+
foo(string);
428+
```
429+
420430
Generic function with multiple types:
421431
```jai
422-
foo :: (a: $A, b: $B, c: $C) {
423-
// use a or b or c here
432+
foo :: (a: $A, b: $B) {
433+
// do something
424434
}
425435
```
426436

427-
Polymorphic structs:
437+
Generic structs:
428438
```jai
429439
Box :: struct(T: Type) {
430440
value: T;
431441
};
432442
433-
b: Box(int);
434-
b.value = 5;
435-
print("type = %", a.T); // you can quiry the type of a stuct like this (prints out "type = int")
443+
box: Box(int);
444+
box.value = 5;
445+
print("type = %", box.T); // you can quiry the type of a stuct like this (prints out "type = int")
436446
```
437447

438448
Jai also supports type constraints such as `$T/SomeStruct` and `$T/interface SomeStruct`, which are similar to traits or interfaces.

0 commit comments

Comments
 (0)