Skip to content

Commit 6ae8ae4

Browse files
committed
very rough interface blob
1 parent 439d2cb commit 6ae8ae4

1 file changed

Lines changed: 64 additions & 1 deletion

File tree

content/posts/jai-guide.md

Lines changed: 64 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -516,7 +516,70 @@ print("type = %", box.T); // you can quiry the type of a stuct like this (prints
516516

517517
## Interfaces / Traits / Constraints
518518

519-
todo `/`, `interface`, `$T/SomeStruct`, `$T/interface SomeStruct`
519+
todo
520+
521+
uses things like `/`, `interface`, `$T/SomeStruct`, `$T/interface SomeStruct`
522+
523+
When working with polymorphic procedures and structs, there's a lightweight syntax for restricting the type of the argument. It looks like: `f :: (x: $T/SomeType) { ... }`
524+
525+
`$T/Object` indicates that the `$T` must be a parameterized struct of the type `Object`
526+
527+
```jai
528+
HashTable :: struct (K: Type, V: Type, N: int) {
529+
keys: [N]K;
530+
values: [N]V;
531+
}
532+
533+
function :: (table: $T/HashTable, key: T.K, value: T.V) {
534+
// do stuff
535+
}
536+
537+
// implicit polymorphism version
538+
function :: (table: Table, key: table.K, value: table.V) {
539+
// do stuff
540+
}
541+
```
542+
543+
`$T/interface` Object indicates that the `$T` must have the fields that `Object` has. `$T/interface` accepts only types that contain members declared in the target struct.
544+
545+
```jai
546+
Vec3 :: struct {
547+
x, y, z: float;
548+
}
549+
550+
OtherVec3 :: struct {
551+
x, y, z: float;
552+
}
553+
554+
dot_product :: (a: $T/interface Vec3, b: T) -> float {
555+
return a.x * b.x + a.y * b.y + a.z * b.z;
556+
}
557+
558+
main :: () {
559+
another: OtherVec3;
560+
product := dot_product(another, another);
561+
}
562+
```
563+
564+
```jai
565+
NamedType :: struct {
566+
name: string;
567+
}
568+
569+
foo :: (x: $T/interface NamedType) {
570+
// do something
571+
}
572+
573+
// Any struct with the same member names and types as 'NamedType' can be passed
574+
// as an argument to 'foo'. This includes just a NamedType, but then it's
575+
// pointless to use 'interface'. It's more for cases like this:
576+
577+
SomeThing :: struct {
578+
name: string;
579+
tag: string;
580+
type: Type;
581+
}
582+
```
520583

521584
## Strings
522585

0 commit comments

Comments
 (0)