七月的泛型

  1. struct RepoT {
  2. db DB
  3. }
  4. fn new_repoT⟩(db DB) RepoT {
  5. return RepoT⟩{db: db}
  6. }
  7. // This is a generic function. V will generate it for every type it's used with.
  8. fn (r RepoT⟩) find_by_id(id int) ?T {
  9. table_name := T.name // in this example getting the name of the type gives us the table name
  10. return r.db.query_oneT⟩('select * from $table_name where id = ?', id)
  11. }
  12. db := new_db()
  13. users_repo := new_repoUser⟩(db)
  14. posts_repo := new_repoPost⟩(db)
  15. user := users_repo.find_by_id(1)?
  16. post := posts_repo.find_by_id(1)?

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