V语言 (Vlang) 发布 0.4.1,安全快速可编译的静态语言

V语言 (Vlang) 0.4.1 已发布。主要变化集中在改进语言特性、解析器、标准库,以及编译器内部相关的变化等。

  • 实现Enum.from_string(name string)将字符串转换为枚举值
  • 禁止使用未初始化的函数指针
  • 使用默认 expr 修复匿名结构
  • 支持使用 const 作为枚举值
  • 禁止将静态函数声明为方法接收者 (method receivers)
  • 修复for i++; i<10; i++ {

详情查看 release notes


V 是一个集合了 Go 的简单和 Rust 的安全特性的静态语言,作者表示 V 与 Go 非常相似,如果你了解 Go,那么就已经了解 80% 的 V。V 在 Go 的基础上进行改进之处:https://vlang.io/compare#go

V 主要特性

  • 简单(作者声称可以在不到一小时内学习 V)
  • 快速编译(编译器只有 400kb,而且无第三方依赖)
  • 易于开发:V 在不到一秒钟的时间内完成编译
  • 安全:没有 null、没有全局变量、没有未定义的值、边界检测、默认使用 Immutable 结构体
  • 支持 C/C++ 转换
  • 方便使用的交叉编译
  • 提供跨平台 UI 库
  • 内置图形库
  • 内置 ORM
  • 内置 Web 框架
  • ……

示例代码

数据库访问:

struct User { /* ... */ }
struct Post { /* ... */ }
struct DB   { /* ... */ }

struct Repo <T> {
    db DB
}

fn new_repo<T>(db DB) Repo {
    return Repo<T>{db: db}
}

fn (r Repo) find_by_id(id int) T? { // `?` means the function returns an optional
    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) or {
        eprintln('User not found')
        return
    }
    post := posts_repo.find_by_id(1) or {
        eprintln('Post not found')
        return
    }
} 

网络开发:

struct Story {
    title string
}

// Fetches top HN stories in 8 coroutines 
fn main() {
    resp := http.get('https://hacker-news.firebaseio.com/v0/topstories.json')?
    ids := json.decode([]int, resp.body)?
    mut cursor := 0
    for _ in 0..8 {
        go fn() {
            for  {
                lock { // Without this lock the program will not compile 
                    if cursor >= ids.len {
                        break
                    }
                    id := ids[cursor]
                    cursor++
                }
                resp := http.get('https://hacker-news.firebaseio.com/v0/item/$id.json')? 
                story := json.decode(Story, resp.body)?
                println(story.title)
            }
        }()
    }
    runtime.wait() // Waits for all coroutines to finish 
} 

猜你喜欢

转载自www.oschina.net/news/256900/vlang-0-4-1-released