洞见(1): zig 编程语言

洞见最新最有价值项目:本期介绍 Zig 编程语言

简介

Zig 是一个现代编程通用编程语言,是C语言的有力竞争者。

Zig is a general-purpose programming language and toolchain for maintaining robust, optimal, and reusable software.

主页地址:https://ziglang.org/
中文主页:https://ziglang.org/zh/

特性

  • 小巧简洁的语言
  • 编译期代码执行
  • 用Zig维护代码

更多可以直接查看上面的主页里的描述。

克隆源码

zig 有多种方式安装:https://ziglang.org/zh/learn/getting-started/

zig 还没有发布1.0,因此直接从源代码构建是值得尝试的。

克隆源码:

git clone https://github.com/ziglang/zig.git

或者从 gitcode 上的镜像克隆

git clone https://gitcode.net/mirrors/ziglang/zig.git

编译

环境要求

  • cmake >= 2.8.12
  • gcc >= 7.0.0 或者 clang >= 6.0.0

编译命令:

  1. mkdir build
  2. cd build
  3. cmake ..
  4. make install

如果在Mac系统下,需要保证

  1. 使用brew install llvm安装llvm
  2. 使用cmake .. -DCMAKE_PREFIX_PATH=$(brew --prefix llvm) -DCMAKE_INSTALL_PREFIX=/usr/local命令编译

查看 zig 命令选项

掌握一个编程语言,很大程度上也是在掌握这个编程语言的工具链的过程。 zig 编程语言的使用,可以从掌握 zig 命令本身开始。直接在控制台上输入zig 并回车即可看到选项信息:

info: Usage: zig [command] [options]

Commands:

  build            Build project from build.zig
  init-exe         Initialize a `zig build` application in the cwd
  init-lib         Initialize a `zig build` library in the cwd

  ast-check        Look for simple compile errors in any set of files
  build-exe        Create executable from source or object files
  build-lib        Create library from source or object files
  build-obj        Create object from source or object files
  fmt              Reformat Zig source into canonical form
  run              Create executable and run immediately
  test             Create and run a test build
  translate-c      Convert C code to Zig code

  ar               Use Zig as a drop-in archiver
  cc               Use Zig as a drop-in C compiler
  c++              Use Zig as a drop-in C++ compiler
  dlltool          Use Zig as a drop-in dlltool.exe
  lib              Use Zig as a drop-in lib.exe
  ranlib           Use Zig as a drop-in ranlib

  env              Print lib path, std path, cache directory, and version
  help             Print this help and exit
  libc             Display native libc paths file or validate one
  targets          List available compilation targets
  version          Print version number and exit
  zen              Print Zen of Zig and exit

General Options:

  -h, --help       Print command-specific usage

Debug Commands:

  changelist       Compute mappings from old ZIR to new ZIR

error: expected command argument

注意最后一行,error: expected command argument 提示需要在 zig 命令后带有命令参数,我们什么都没有带于是zig就输出了选项帮助信息。如果直接用zig -h或者zig --help则是常规的查看选项帮助的方式。

zig 之禅

每个编程语言都有其对应的设计哲学,许多语言会用 zen of xxx 来表示这个语言的哲学。这里的 zen 是“禅”的意思,表示一种深入思考后的智慧。

例如,python 语言在语言文档页上也有这样的一个页面:
PEP 20 – The Zen of Python: https://www.python.org/dev/peps/pep-0020/

例如,也有人给 C++ 编程语言写了这样的一个页面:
The Zen Of C++: https://www.experts-exchange.com/articles/10157/The-Zen-Of-C.html

例如,Unix 操作系统也有它的哲学:
Basics of the Unix Philosophy:https://homepage.cs.uri.edu/~thenry/resources/unix_art/ch01s06.html

zig 编程语言直接在命令行里内置了它的设计哲学,使用如下的命令

zig zen

可以看到,zig 的设计哲学是:

* Communicate intent precisely.
* Edge cases matter.
* Favor reading code over writing code.
* Only one obvious way to do things.
* Runtime crashes are better than bugs.
* Compile errors are better than runtime crashes.
* Incremental improvements.
* Avoid local maximums.
* Reduce the amount one must remember.
* Focus on code rather than style.
* Resource allocation may fail; resource deallocation must succeed.
* Memory is a resource.
* Together we serve the users.

程序员可以从这些条目里获得启发,哪怕不使用zig,好的哲学在其他开发语境里也一样是重要的。

查看 zig 的版本号

可以用命令直接查看zig的版本号:

zig version

结果如下:

0.10.0-dev.1058+eaf1c97ce

查看 zig 的环境变量

命令:

zig env

可以看到 zig 的环境变量非常的人性化(Mac系统):

{
    
    
 "zig_exe": "/usr/local/bin/zig",
 "lib_dir": "/usr/local/bin/lib/zig",
 "std_dir": "/usr/local/bin/lib/zig/std",
 "global_cache_dir": "/Users/username/.cache/zig",
 "version": "0.10.0-dev.1058+eaf1c97ce"
}

列出了这些信息

  • zig_exe : zig 命令所在的路径
  • lib_dir : zig 的 lib 路径
  • std_dir : zig 标准库的位置,可以看到是 lib_dir 的一个子目录
  • global_cache_dir : 缓存目录
  • version : 版本号

从这里逐渐可以看到,zig 的命令体系类似 git 的方式,采用的是 command action 的模式,比较友好而现代。

创建一个 zig 命令行程序

使用 zig 命令可以快速创建一个命令行程序,先创建一个 test 目录,然后在目录下执行命令

zig init-exe

生成的目录结构如下:

.
├── build.zig
└── src
    └── main.zig

其中,src/ 目录是源码目录,而 build.zig 则是构建项目的“脚本”,其本身也是一个zig程序,这带来了很强的一致性:源码和源码构建脚本使用的是一种语言。查看下 src/main.zig的hello world 代码:

const std = @import("std");

pub fn main() anyerror!void {
    std.log.info("All your codebase are belong to us.", .{});
}

test "basic test" {
    try std.testing.expectEqual(10, 3 + 7);
}

源码解释如下:

  • 第一行使用 @import(“std”) 的方式导入了标准库。
  • 接下来是程序入口main函数,在函数内使用标准库打印了一行信息。
  • 接下来是一段单元测试程序

构建 zig 程序

使用 zig 的命令行即可轻松完成构建:

zig build

构建过程的命令行非常干净,没有显示满屏的构建信息,而是就地刷新信息行,构建完成后的目录结构如下:

.
├── build.zig
├── src
│   └── main.zig
├── zig-cache
│   ├── h
│   │   ├── 237f592bfc87d556dffba90a015637a1.txt
│   │   ├── ae3ffb1f119a3161a4cc2f48480dfa9d.txt
│   │   └── timestamp
│   ├── o
│   │   ├── 23650d5ec66547ed61e5e4072ce70ba7
│   │   │   ├── build
│   │   │   └── build.o
│   │   ├── 99b9e6b82f4011e2eb15a72ca8fbb5f3
│   │   │   ├── test
│   │   │   └── test.o
│   │   ├── b91f14aec3e67ae9026c15e937a2e811
│   │   │   └── builtin.zig
│   │   └── c8809ea18e0907e87e2698d775132309
│   │       └── builtin.zig
│   ├── tmp
│   └── z
│       ├── c8d7e1e8c507700e93104fdc5bbd7fcd
│       └── dd90fc6dc4731d7ca192082b0db949aa
└── zig-out
    └── bin
        └── test

其中 zig-cache 目录是程序构建的中间目录,而 zig-out 则是程序的构建输出目录。可以看到bin目录下生成了一个test程序。

运行 zig 程序

可以直接运行生成的二进制程序:

./zig-out/bin/test

程序输出了一行信息:

info: All your codebase are belong to us.

直接从源码运行

此外,也可以使用 run 命令来直接运行目标源码

zig run src/main.zig

可以看到zig会直接编译并运行程序,结果如下:

info: All your codebase are belong to us.

执行单元测试

src/main.zig 里有一段单元测试代码:

test "basic test" {
    
    
    try std.testing.expectEqual(10, 3 + 7);
}

实际上,zig支持直接用命令对含有单元测试的源码执行测试:

zig test src/main.zig

可以看到结果:

All 1 tests passed.

掌握现代编程语言

综合来看,zig 作为一种新的现代编程语言,从zig 命令行来看,整个设计十分简洁,易于使用。它的核心设计之一是减少“魔法”:

  • 没有隐式控制流
  • 没有隐式内存分配
  • 没有预处理器,没有宏

根据一项统计,工程师平均有 70% 的时间花在了读代码上,读代码痛点之一是代码里充满了各种“隐藏的魔法”,zig在这方面的设计是很有价值的。不同的编程语言代表了不同的目标开发环境和平台,zig是C语言的一个有力竞争者。掌握现代编程语言,可以从使用zig编写日常处理的一些命令行小程序开始。

–end–

猜你喜欢

转载自blog.csdn.net/community_717/article/details/123321148