From 6c267f1c74a193bfca6cfc69d5358358d5e94273 Mon Sep 17 00:00:00 2001 From: Nick Treleaven Date: Sat, 24 Oct 2020 18:37:14 +0100 Subject: [PATCH] doc: explain current limitations of generics (#6674) --- doc/docs.md | 37 +++++++++++++++++++++++-------------- 1 file changed, 23 insertions(+), 14 deletions(-) diff --git a/doc/docs.md b/doc/docs.md index d94263c84e..497d083b8e 100644 --- a/doc/docs.md +++ b/doc/docs.md @@ -1800,15 +1800,21 @@ fn (r Repo) find_by_id(id int) ?T { } db := new_db() -users_repo := new_repo(db) -posts_repo := new_repo(db) -user := users_repo.find_by_id(1)? -post := posts_repo.find_by_id(1)? +users_repo := new_repo(db) // returns Repo +posts_repo := new_repo(db) // returns Repo +user := users_repo.find_by_id(1)? // find_by_id +post := posts_repo.find_by_id(1)? // find_by_id ``` +At the moment only one type parameter named `T` is supported. + +Currently generic function definitions must declare their type parameters, but in +future V will infer generic type parameters from single-letter type names in +runtime parameter types. This is why `find_by_id` can omit ``, because the +receiver argument `r` uses a generic type `T`. Another example: ```v -fn compare(a, b T) int { +fn compare(a T, b T) int { if a < b { return -1 } @@ -1818,17 +1824,20 @@ fn compare(a, b T) int { return 0 } -println(compare(1,0)) // Outputs: 1 -println(compare(1,1)) // 0 -println(compare(1,2)) // -1 +// compare +println(compare(1, 0)) // Outputs: 1 +println(compare(1, 1)) // 0 +println(compare(1, 2)) // -1 -println(compare('1','0')) // Outputs: 1 -println(compare('1','1')) // 0 -println(compare('1','2')) // -1 +// compare +println(compare('1', '0')) // Outputs: 1 +println(compare('1', '1')) // 0 +println(compare('1', '2')) // -1 -println(compare(1.1, 1.0)) // Outputs: 1 -println(compare(1.1, 1.1)) // 0 -println(compare(1.1, 1.2)) // -1 +// compare +println(compare(1.1, 1.0)) // Outputs: 1 +println(compare(1.1, 1.1)) // 0 +println(compare(1.1, 1.2)) // -1 ```