七月的泛型

1. struct Repo⟨T⟩ {
2. db DB
3. }

5. fn new_repo⟨T⟩(db DB) Repo⟨T⟩ {
6. return Repo⟨T⟩{db: db}
7. }

9. // This is a generic function. V will generate it for every type it's used with.
10. fn (r Repo⟨T⟩) find_by_id(id int) ?T {
11. table_name := T.name // in this example getting the name of the type gives us the table name
12. return r.db.query_one⟨T⟩('select * from $table_name where id = ?', id)
13. }

15. db := new_db()
16. users_repo := new_repo⟨User⟩(db)
17. posts_repo := new_repo⟨Post⟩(db)
18. user := users_repo.find_by_id(1)?
19. post := posts_repo.find_by_id(1)?

为了方便阅读,允许使用⟨⟩代替<>。vfmt最终会将⟨⟩替换为<>。