×
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语言 可选类型(Option types)


struct User {
	id int
}
 
struct Repo {
	users []User
}
 
fn new_repo() Repo {
        user := User{id:10}
        return Repo {
                users: [user]
        }
}
 
fn (r Repo) find_user_by_id(id int) User? {
	for user in r.users {
		if user.id == id {
			// V automatically wraps this into an option type  
			return user
		}
	}
	return error('User $id not found')
}
 
fn main() {
	repo := new_repo()
	user := repo.find_user_by_id(10) or { // Option types must be handled by `or` blocks  
		return  // `or` block must end with `return`, `break`, or `continue`  
	}
	println(user.id) // ==> "10"  
}

将函数"升级"为可选函数所需的工作量很小,你只需要添加一个 ?来返回类型并在出现错误时返回错误。

如果你不需要返回一个错误,那么你可以简单地返回 None。(*None目前还没有实现)


分类导航

关注微信下载离线手册

bootwiki移动版 bootwiki
(群号:472910771)