Skip to content

Commit 3186168

Browse files
committed
polymorphism start
1 parent 72b2960 commit 3186168

1 file changed

Lines changed: 36 additions & 0 deletions

File tree

content/posts/odin-guide.md

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -553,6 +553,42 @@ foo :: proc(a: Vector3) -> f32 {
553553

554554
The odin language specifically uses a form of generics called "Parametric Polymorphism"
555555

556+
In odin you can specify that a variable or type needs to be a compile time constant by using the `$` dollar sign, which is often required for polymorphism.
557+
558+
Both variables and types can be tagged with the `$` sign.
559+
560+
Here are examples of how to do generics in the odin language:
561+
562+
```odin
563+
proc($T: typeid) // T can be any type
564+
proc($N: int) // N has to be an integer value
565+
proc(x: $T) // T represents the type of the x variable inside the procedure scope
566+
proc($A: $B) // A can be of any type, B then represents the type of A inside the procedure scope
567+
568+
// strucs can have polymorphic parameters
569+
SomeStruct :: struct($T: typeid) {
570+
size: T
571+
}
572+
foo: SomeStruct(int)
573+
574+
// "implicit" polymorphism implies that the type of a parameter is inferred from its input ($A: $B)
575+
foo :: proc($N: $I, $T: typeid) {
576+
// N is the constant value passed
577+
// I is the type of N
578+
// T is the type passed
579+
}
580+
example := foo(4, int)
581+
582+
// in some cases, you may want to specify that a type must be a specialization of a certain type, this is done with a slash
583+
proc(table: $T/Table) // allow types that are specializations of a table type
584+
proc($T: typeid/[]S) // allow types that are specializations of a slice
585+
proc($T: typeid/[]$S) // allow types that are specializations of a compile time (polymorphic) slice
586+
587+
// where clauses can be used to constrain inputs
588+
proc(x: int) where len(x) > 1 {}
589+
proc(x: int) where type_of(x) == int {}
590+
```
591+
556592
## Strings
557593

558594
## Function Pointers / Function Types

0 commit comments

Comments
 (0)