@@ -565,7 +565,9 @@ <h2 id=option>Option types</h2>
565
565
566
566
567
567
< h2 id=generics> Generics</ h2>
568
- < pre> struct Repo <T> {
568
+ < pre> import database
569
+
570
+ struct Repo <T> {
569
571
db DB
570
572
}
571
573
@@ -576,25 +578,28 @@ <h2 id=generics>Generics</h2>
576
578
return Repo<T> {db: db}
577
579
}
578
580
579
- fn (db DB) query_one<T> (query string, id int) T? {
580
- < comment> // Return a value of type T from the database, or an error.
581
- // Implementation omitted...</ comment>
582
- }
583
-
584
- < comment> // This is a generic receiver function. V will generate it for every Repo instance it's used with.
585
- // T is inferred from the receiver argument. Again <T> is implied by just writing Repo:
581
+ < comment> // This is a generic method. V will generate it for every Repo instance it's used with.
582
+ // Again <T> is implied by just writing Repo for the receiver type, so V makes the method take <T> too:
586
583
// fn (r Repo<T> ) find_by_id<T> (id int) T?</ comment>
587
584
fn (r Repo) find_by_id(id int) T? {
588
585
table_name := T.name < comment> // in this example getting the name of the type gives us the table name</ comment>
586
+ < comment> //lookup a value of type T from the database, or return an error</ comment>
589
587
return db.query_one<T> ('select * from $table_name where id = ?', id)
590
588
}
591
589
590
+ struct User { name string }
591
+ struct Post { text string }
592
+
592
593
fn main() {
593
594
db := new_db()
594
595
users_repo := new_repo<User> (db)
595
596
posts_repo := new_repo<Post> (db)
597
+ < comment> // find_by_id< User> is inferred from users_repo:</ comment>
596
598
user := users_repo.find_by_id(1)?
599
+ < comment> // find_by_id< Post> is inferred from posts_repo:</ comment>
597
600
post := posts_repo.find_by_id(1)?
601
+ println(user.name)
602
+ println(post.text)
598
603
}
599
604
</ pre>
600
605
0 commit comments