@@ -1800,15 +1800,21 @@ fn (r Repo<T>) find_by_id(id int) ?T {
1800
1800
}
1801
1801
1802
1802
db := new_db()
1803
- users_repo := new_repo<User>(db)
1804
- posts_repo := new_repo<Post>(db)
1805
- user := users_repo.find_by_id(1)?
1806
- post := posts_repo.find_by_id(1)?
1803
+ users_repo := new_repo<User>(db) // returns Repo<User>
1804
+ posts_repo := new_repo<Post>(db) // returns Repo<Post>
1805
+ user := users_repo.find_by_id(1)? // find_by_id<User>
1806
+ post := posts_repo.find_by_id(1)? // find_by_id<Post>
1807
1807
```
1808
+ At the moment only one type parameter named ` T ` is supported.
1809
+
1810
+ Currently generic function definitions must declare their type parameters, but in
1811
+ future V will infer generic type parameters from single-letter type names in
1812
+ runtime parameter types. This is why ` find_by_id ` can omit ` <T> ` , because the
1813
+ receiver argument ` r ` uses a generic type ` T ` .
1808
1814
1809
1815
Another example:
1810
1816
``` v
1811
- fn compare<T>(a, b T) int {
1817
+ fn compare<T>(a T , b T) int {
1812
1818
if a < b {
1813
1819
return -1
1814
1820
}
@@ -1818,17 +1824,20 @@ fn compare<T>(a, b T) int {
1818
1824
return 0
1819
1825
}
1820
1826
1821
- println(compare<int>(1,0)) // Outputs: 1
1822
- println(compare<int>(1,1)) // 0
1823
- println(compare<int>(1,2)) // -1
1827
+ // compare<int>
1828
+ println(compare(1, 0)) // Outputs: 1
1829
+ println(compare(1, 1)) // 0
1830
+ println(compare(1, 2)) // -1
1824
1831
1825
- println(compare<string>('1','0')) // Outputs: 1
1826
- println(compare<string>('1','1')) // 0
1827
- println(compare<string>('1','2')) // -1
1832
+ // compare<string>
1833
+ println(compare('1', '0')) // Outputs: 1
1834
+ println(compare('1', '1')) // 0
1835
+ println(compare('1', '2')) // -1
1828
1836
1829
- println(compare<float>(1.1, 1.0)) // Outputs: 1
1830
- println(compare<float>(1.1, 1.1)) // 0
1831
- println(compare<float>(1.1, 1.2)) // -1
1837
+ // compare<f64>
1838
+ println(compare(1.1, 1.0)) // Outputs: 1
1839
+ println(compare(1.1, 1.1)) // 0
1840
+ println(compare(1.1, 1.2)) // -1
1832
1841
```
1833
1842
1834
1843
0 commit comments