Generics
Examples in
V
struct Repo {
db DB
}
fn new_repo(db DB) Repo {
return Repo{db: db}
}
// This is a generic function. V will generate it for every type it's used with.
fn (r Repo) find_by_id(id int) ?T {
table_name := T.name // in this example getting the name of the type gives us the table name
return r.db.query_one('select * from $table_name where id = ?', id)
}
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)?