×
V语言 简介V语言 Hello WorldV语言 注释V语言 函数V语言 变量V语言 基本类型V语言 字符串(Strings)V语言 数组(Arrays)V语言 MapsV语言 IfV语言 For循环V语言 SwitchV语言 结构体(Structs)V语言 方法(Methods)V语言 可变接收器及纯函数V语言 常量(Constants)V语言 模块(Modules)V语言 接口(Interfaces)V语言 枚举(Enums)V语言 可选类型(Option types)V语言 泛型(Generics)V语言 并发(Concurrency)V语言 JSON解析V语言 测试(Testing)V语言 内存管理V语言 有限的运算符重载V语言 热更新V语言 调用C函数示例V语言 转换C/C++代码到V语言V语言 交叉编译V语言 关键词

V语言 泛型(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)
}
 
fn main() {
	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)?
} 



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

分类导航

关注微信下载离线手册

bootwiki移动版 bootwiki
(群号:472910771)