泛型(Generics)


struct Repo⟨T⟩ {
    db DB
}

fn new_repo⟨T⟩(db DB) Repo⟨T⟩ {
    return Repo⟨T⟩{db: db}
}

// This is a generic function. V will generate it for every type it's used with. 
fn (r Repo⟨T⟩) 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⟨T⟩('select * from $table_name where id = ?', id)
}

db := new_db()
users_repo := new_repo⟨User⟩(db)
posts_repo := new_repo⟨Post⟩(db)
user := users_repo.find_by_id(1)? 
post := posts_repo.find_by_id(1)?

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

The initial version of V had generics because arrays and maps were built with them. Later I figured out a way to implement these data structures without generics. This simplified code greatly.

Since I no longer needed them, they were moved to a branch, because maintaining generics is tough. Generics will not be available when the language is released in June, but they should be back by July.

摘录自V语言作者Alex

results matching ""

    No results matching ""