Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Rust 语法 #139

Open
nonocast opened this issue Nov 27, 2020 · 0 comments
Open

Rust 语法 #139

nonocast opened this issue Nov 27, 2020 · 0 comments

Comments

@nonocast
Copy link
Owner

nonocast commented Nov 27, 2020

Rust是由Mozilla主导开发的通用、编译型编程语言。设计准则为“安全、并发、实用”,支持函数式、并发式、过程式以及面向对象的编程风格。
Rust语言原本是Mozilla员工Graydon Hoare的私人计划,而Mozilla于2009年开始赞助这个计划,并且在2010年首次揭露了它的存在。也在同一年,其编译器源代码开始由原本的OCaml语言转移到用Rust语言,进行bootstrapping工作,称做rustc,并于2011年实际完成。这个可自我编译的编译器在架构上采用了LLVM做为它的后端。
第一个有版本号的Rust编译器于2012年1月发布。Rust 1.0是第一个稳定版本,于2015年5月15日发布。
Rust是在完全开放的情况下进行开发,并且相当欢迎社区的反馈。在1.0稳定版之前,语言设计也因为透过撰写Servo网页浏览器排版引擎和rustc编译器本身,而有进一步的改善。虽然它由Mozilla资助,但它其实是一个共有项目,有很大部分的代码是来自于社区的贡献者。

第一个Rust程序

hello.rs

fn main() {
  println!("hello world");
}
~ rustc hello.rs
~ ./hello
hello world

语言特性

  • 静态语言
  • 面向对象
  • 需要编译
  • 强类型
  • 最接近C++

工具链

  • rustc: compiler
  • cargo: build tool, 类似make, yarn

通过cargo建立hello world, cargo run会自动cargo build,你可以将两步分离:

~ cargo new hello && cd $_
~ cargo run   
   Compiling hello v0.1.0 (/Users/nonocast/Develop/hello/hello-rust/hello)
    Finished dev [unoptimized + debuginfo] target(s) in 1.68s
     Running `target/debug/hello`
Hello, world!

其中自动生成的Cargo.toml有点package.json的意思,

[package]
name = "hello"
version = "0.1.0"
authors = ["nonocast <nonocast@gmail.com>"]
edition = "2018"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]

变量和可变性

fn main() {
  let x = 5;
  println!("x: {}", x);
}
  • let定义的变量是immutable variable,即不可变的变量,不能二次赋值,这个和大多数语言都不同
  • 需要通过mut来声明一个可以变的变量,let mut x = 5
  • 主要还是认为变量大多数都是首次赋值才有意义
  • 不可变的变量和常量的区别在于: 常量通过const定义,在编译时就需要确定值,只能是常量表达式,而不能是函数调用的结果,所以核心区别在于确定值的时机,一个是编译时,一个是运行时
  • Shadowing允许多次let一个同名的变量,这个也蛮奇怪,尽量还是避免
fn main() {
  let x = 5;
  println!("x: {}", x);
  let x = 7;
  println!("x: {}", x);
}

数据类型包括:

  • scalar (标量): integers, floatings, booleans, chars
  • compound (复合): tuple, array

说明:

  • char用单引号,string用双引号, 单字符采用four bytes, 采用unicode表示
  • boolean: true和false
  • floating有32bits的f32和64bits的f64, 和cpu对齐就好
  • integer包括i8/u8-i128/u128, 考虑到不同cpu的宽度
  • Rust内置的复合类型只有tuple和array, let a = [1, 2, 3, 4, 5]

函数

fn main() {
  println!("result: {}", hello2("nonocast"));
}

fn hello0() {
  println!("hello");
}

fn hello1(name: &str) {
  println!("hello {}", name);
}

fn hello2(name: &str) -> i32 {
  println!("hello {}", name);
  return 7;
}

todo

  • control flow
  • class
  • module

参考资料:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant