官网:https://www.rust-lang.org/zh-CN/learn/get-started
Windows:按官网指示操作
Mac 安装:
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh

rustup update
rustup self uninstall
rustc --version
rustup doc可在浏览器打开本地文档➜ cargo --version
cargo 1.67.1 (8ecd4f20a 2023-01-10)
~
➜ rustc --version
rustc 1.67.1 (d5a82bbd2 2023-02-07)
~
➜ rustup doc
编写Rust程序
➜ mkdir rust
~
➜ cd rust
~/rust
➜ mkdir hello_world
~/rust
➜ cd hello_world
~/rust/hello_world
➜ code .
~/rust/hello_world
➜ pwd
/Users/qiaopengjun/rust/hello_world
~/rust/hello_world via ? 1.67.1
➜ mv hello_world.rs main.rs
~/rust/hello_world via ? 1.67.1
➜ rustc main.rs
~/rust/hello_world via ? 1.67.1
➜ ls
main main.rs
➜ ./main
Hello World!
main.rs`文件
fn main() {
println!("Hello World!");
}
fn main(){}
main函数很特别:它是每个Rust可执行程序最先运行的代码printIn!("Hello, world!");
rustc源文件名
rustc main.rs.pdb文件,里面包含调试信息~/rust/hello_world via ? 1.67.1
➜ cargo --version
cargo 1.67.1 (8ecd4f20a 2023-01-10)
cargo new hello_cargo
hello_cargohello_cargo
main.rs.gitignore
~/rust
➜ cargo new hello_cargo
Created binary (application) `hello_cargo` package
~/rust
➜ ls
hello_cargo hello_world
~/rust
➜ cd hello_cargo
hello_cargo on master [?] via ? 1.67.1
➜ ls
Cargo.toml src
hello_cargo on master [?] via ? 1.67.1
➜ ➜ ls
Cargo.toml src
Cargo.toml
src/main.rs./target/debug/hello_cargo或.\target\debug\hello_cargo.exe(Windows)cargo build会在顶层目录生成cargo.lock文件
cargo runhello_cargo on master [?] is ? 0.1.0 via ? 1.67.1
➜ cargo run
Compiling hello_cargo v0.1.0 (/Users/qiaopengjun/rust/hello_cargo)
Finished dev [unoptimized + debuginfo] target(s) in 0.38s
Running `target/debug/hello_cargo`
Hello, world!
hello_cargo on master [?] is ? 0.1.0 via ? 1.67.1
➜

cargo check尽量用Cargo

use std::io; // prelude
fn main() {
println!("猜数!");
println!("猜测一个数");
// let mut foo = 1;
// let bar = foo; // immutable
// foo = 2;
let mut guess = String::new();
io::stdin().read_line(&mut guess).expect("无法读取行");
// io::Result Ok Err
println!("你猜测的数是:{}", guess);
}

[rang]https://crates.io/crates/rand
➜ cd rust/guessing_game
guessing_game on main [✘!] is ? 0.1.0 via ? 1.67.1
➜ cargo build
Compiling cfg-if v1.0.0
Compiling ppv-lite86 v0.2.17
Compiling libc v0.2.139
Compiling getrandom v0.2.8
Compiling rand_core v0.6.4
Compiling rand_chacha v0.3.1
Compiling rand v0.8.5
Compiling guessing_game v0.1.0 (/Users/qiaopengjun/rust/guessing_game)
Finished dev [unoptimized + debuginfo] target(s) in 1.08s
guessing_game on main [✘!] is ? 0.1.0 via ? 1.67.1
➜ cargo build
Finished dev [unoptimized + debuginfo] target(s) in 0.03s
guessing_game on main [✘!] is ? 0.1.0 via ? 1.67.1
➜ cargo update

随机数

代码:
use std::io; // prelude
use rand::Rng; // trait
fn main() {
println!("猜数!");
let secret_number = rand::thread_rng().gen_range(1..101);
println!("神秘数字是:{}", secret_number);
println!("猜测一个数");
// let mut foo = 1;
// let bar = foo; // immutable
// foo = 2;
let mut guess = String::new();
io::stdin().read_line(&mut guess).expect("无法读取行");
// io::Result Ok Err
println!("你猜测的数是:{}", guess);
}
use std::io; // prelude
use rand::Rng; // trait
use std::cmp::Ordering; // 枚举类型 三个变体(值)
fn main() {
println!("猜数!");
let secret_number = rand::thread_rng().gen_range(1..101);
println!("神秘数字是:{}", secret_number);
println!("猜测一个数");
// let mut foo = 1;
// let bar = foo; // immutable
// foo = 2;
let mut guess = String::new();
io::stdin().read_line(&mut guess).expect("无法读取行");
// io::Result Ok Err
// shadow
let guess: u32 = guess.trim().parse().expect("Please type a number!"); // \n
println!("你猜测的数是:{}", guess);
match guess.cmp(&secret_number) {
Ordering::Less => println!("Too small!"), // arm
Ordering::Greater => println!("Too big!"),
Ordering::Equal => println!("You win!"),
}
}
use std::io; // prelude
use rand::Rng; // trait
use std::cmp::Ordering; // 枚举类型 三个变体(值)
fn main() {
println!("猜数!");
let secret_number = rand::thread_rng().gen_range(1..101);
// println!("神秘数字是:{}", secret_number);
loop {
println!("猜测一个数");
// let mut foo = 1;
// let bar = foo; // immutable
// foo = 2;
let mut guess = String::new();
io::stdin().read_line(&mut guess).expect("无法读取行");
// io::Result Ok Err
// shadow
let guess: u32 = match guess.trim().parse() {
Ok(num) => num,
Err(_) => {
println!("请输入正确的数字");
continue;
}
};
println!("你猜测的数是:{}", guess);
match guess.cmp(&secret_number) {
Ordering::Less => println!("Too small!"), // arm
Ordering::Greater => println!("Too big!"),
Ordering::Equal => {
println!("You win!");
break;
}
}
}
}
let关键字mut,就可以使变量可变。~/rust
➜ cargo new variables
Created binary (application) `variables` package
~/rust
➜ cd var*
variables on master [?] via ? 1.67.1
➜ code .
variables on master [?] via ? 1.67.1
➜

代码:
fn main() {
println!("Hello, world!");
let mut x = 5;
println!("The value of x is {}", x);
x = 6;
println!("The value of x is {}", x);
}
mut,常量永远都是不可变的const关键字,它的类型必须被标注MAX_POINTSconst MAX_POINTS: u32 = 100_000;// const MAX_POINTS: u32 = 100_000;
fn main() {
// const MAX_POINTS: u32 = 100_000;
println!("Hello, world!");
let mut x = 5;
println!("The value of x is {}", x);
x = 6;
println!("The value of x is {}", x);
let x = x + 1;
let x = x * 2;
println!("The value of x is {}", x);
let spaces = " ";
let spaces = spaces.len();
println!("The length of spaces is {}", spaces);
let guess: u32 = "42".parse().expect("Not a number");
println!("The guess is {}", guess);
}
整数类型
| length | signed | unsigned |
|---|---|---|
| 8-bit | i8 | u8 |
| 16-bit | i16 | u16 |
| 32-bit | i32 | u32 |
| 64-bit | i64 | u64 |
| 128-bit | i128 | u128 |
| arch | isize | usize |
十进制、十六进制、八进制、二进制、byte
// const MAX_POINTS: u32 = 100_000;
fn main() {
// const MAX_POINTS: u32 = 100_000;
println!("Hello, world!");
let mut x = 5;
println!("The value of x is {}", x);
x = 6;
println!("The value of x is {}", x);
let x = x + 1;
let x = x * 2;
println!("The value of x is {}", x);
let spaces = " ";
let spaces = spaces.len();
println!("The length of spaces is {}", spaces);
let guess: u32 = "42".parse().expect("Not a number");
println!("The guess is {}", guess);
// let x = 2.0; // f64
// let y: f32 = 3.0; // f32
// let sum = 5 + 10;
// let difference = 95.5 - 4.3;
// let product = 4 * 30;
// let quotient = 56.7 / 32.2;
// let reminder = 54 % 5;
// let t = true;
// let f: bool = false;
// let x = 'z';
// let y: char = 'a';
// let z = '?';
}
fn main() {
let tup: (i32, f64, u8) = (500, 6.4, 1);
println!("{}, {}, {}", tup.0, tup.1, tup.2);
let (x, y, z) = tup;
println!("{}, {}, {}", x, y, z);
}
let a: [i32; 5] = [1, 2, 3, 4, 5];let a = [3; 5]; 它就相当于:let a = [3, 3, 3, 3, 3];fn main() {
// let a = [1, 2, 3, 4, 5];
let months = [
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December",
];
// let first = months[0];
// let second = months[1];
// let index = 15;
let index = [12, 13, 14, 15];
let month = months[index[1]];
println!("{}", month);
}
fn main() {
another_function();
}
fn another_function() {
println!("Another function");
}
fn main() {
another_function(5, 6); // argument
}
fn another_function(x: i32, y: i32) { // parameter
println!("the value of x is {}", x);
println!("the value of y is {}", y);
}
fn main() {
let y = 6; // 语句
// let x = (let y = 6); // 报错
let x = 5;
let y = {
let x = 1;
x + 3
};
println!("The value of y is {}", y)
}
fn plus_five(x: i32) -> i32 {
x + 5
}
fn main() {
let x = plus_five(6);
println!("The value of x is {}", x);
}
// This is a function
fn five(x: i32) -> i32 {
x + 5
}
/* sdgagaf
sfgagaga */
// This is main function
// The entry point
fn main() {
// call five()
let x = five(6); // 5 + 6
println!("The value of x is: {}", x);
}
fn main() {
println!("Hello, world!");
let number = 7;
if number < 5 {
println!("condition was true");
} else {
println!("condition was false");
}
}
fn main() {
let number = 6;
if number % 4 == 0 {
println!("number is divisible by 4");
} else if number % 3 == 0 {
println!("number is divisible by 3");
} else if number % 2 == 0 {
println!("number is divisible by 2");
} else {
println!("number is not divisible by 4, 3 or 2");
}
}
使用match
fn main() {
let number = 6;
match number {
number if number % 4 == 0 => println!("number is divisible by 4"),
number if number % 3 == 0 => println!("number is divisible by 3"),
number if number % 2 == 0 => println!("number is divisible by 2"),
_ => println!("number is not divisible by 4, 3 or 2"),
}
}
fn main() {
let condition = true;
let number = if condition {5} else {6};
println!("The value of number is {}", number);
}
fn main() {
let mut counter = 0;
let result = loop {
counter += 1;
if counter == 10 {
break counter * 2;
}
};
println!("The result is {}", result);
}
fn main() {
let mut number = 3;
while number != 0 {
println!("{}", number);
number = number - 1;
}
println!("LIFTOFF!!!");
}
fn main() {
let a = [10, 20, 30, 40, 50];
let mut index = 0;
while index < 5 {
println!("the index is {}", a[index]);
index = index + 1;
}
}
fn main() {
let a = [10, 20, 30, 40, 50];
for element in a.iter() {
println!("the value is {}", element);
}
}
fn main() {
for number in (1..4).rev() {
println!("{}", number);
}
println!("LIFTOFF!!!");
}
栈内存 VS 堆内存
存储数据
访问数据
函数调用
所有权存在的原因
fn main() {
// s 不可用
let s = "hello"; // s 可用
// 可以对 s 进行相关操作
} // s 作用域到此结束,s 不再可用
fn main() {
let mut s = String::from("Hello");
s.push_str(", World");
println!("{}", s);
}
String::from来实现let x = 5;
let y = x;
String版本
let s1 = String::from("hello");
let s2 = s1;
fn main() {
let s1 = String::from("Hello");
let s2 = s1.clone();
println!("{}, {}", s1, s2);
}
fn main() {
let x = 5;
let y = x;
println!("{}, {}", x, y);
}
(i32, i32)是(i32, String)不是fn main() {
let s = String::from("Hello, World!");
take_ownership(s);
let x = 5;
makes_copy(x);
println!("x: {}", x);
}
fn take_ownership(some_string: String) {
println!("{}", some_string)
}
fn makes_copy(some_number: i32) {
println!("{}", some_number);
}
fn main() {
let s1 = gives_ownership();
let s2 = String::from("hello");
let s3 = takes_and_gives_back(s2);
}
fn gives_ownership() -> String {
let some_string = String::from("hello");
some_string
}
fn takes_and_gives_back(a_string: String) -> String {
a_string
}
fn main() {
let s1 = String::from("hello");
let (s2, len) = calculate_length(s1);
println!("The length of '{}' is {}.", s2, len);
}
fn calculate_length(s: String) -> (String, usize) {
let length = s.len();
(s, length)
}
fn main() {
let s1 = String::from("Hello");
let len = calculate_length(&s1);
println!("The length of '{}' is {}.", s1, len);
}
fn calculate_length(s: &String) -> usize {
s.len()
}
fn main() {
let mut s = String::from("Hello");
{
let s1 = &mut s;
}
let s2 = &mut s;
}
fn main() {
let mut s = String::from("Hello");
let r1 = &s;
let r2 = &s;
let s1 = &mut s; // 报错
println!("{} {} {}", r1, r2, s1);
}
fn main() {
let mut s = String::from("Hello world");
let word_index = first_world(&s);
println!("{}", word_index);
}
fn first_world(s: &String) -> usize {
let bytes = s.as_bytes();
for (i, &item) in bytes.iter().enumerate() {
if item == b' ' {
return i;
}
}
s.len()
}
fn main() {
let s = String::from("Hello world");
let hello = &s[0..5];
let world = &s[6..11];
println!("{}, {}", hello, world);
}
fn main() {
let s = String::from("Hello world");
let word_index = first_world(&s);
println!("{}", word_index);
}
fn first_world(s: &String) -> &str {
let bytes = s.as_bytes();
for (i, &item) in bytes.iter().enumerate() {
if item == b' ' {
return &s[..i];
}
}
&s[..]
}
fn main() {
let s = "Hello world";
println!("{}", s)
}
fn first_word(s: &String) -> &str {fn first_word(s: &str) -> &str {
fn main() {
let my_string = String::from("Hello world");
let word_index = first_world(&my_string[..]);
println!("{}", word_index);
let my_string_literal = "hello world";
let word_literal = first_world(my_string_literal);
println!("word_literal: {}", word_literal);
}
fn first_world(s: &str) -> &str {
let bytes = s.as_bytes();
for (i, &item) in bytes.iter().enumerate() {
if item == b' ' {
return &s[..i];
}
}
&s[..]
}
fn main() {
let a = [1, 2, 3, 4, 5];
let slice = &a[1..3];
}
我正在寻找执行以下操作的正确语法(在Perl、Shell或Ruby中):#variabletoaccessthedatalinesappendedasafileEND_OF_SCRIPT_MARKERrawdatastartshereanditcontinues. 最佳答案 Perl用__DATA__做这个:#!/usr/bin/perlusestrict;usewarnings;while(){print;}__DATA__Texttoprintgoeshere 关于ruby-如何将脚
我试图获取一个长度在1到10之间的字符串,并输出将字符串分解为大小为1、2或3的连续子字符串的所有可能方式。例如:输入:123456将整数分割成单个字符,然后继续查找组合。该代码将返回以下所有数组。[1,2,3,4,5,6][12,3,4,5,6][1,23,4,5,6][1,2,34,5,6][1,2,3,45,6][1,2,3,4,56][12,34,5,6][12,3,45,6][12,3,4,56][1,23,45,6][1,2,34,56][1,23,4,56][12,34,56][123,4,5,6][1,234,5,6][1,2,345,6][1,2,3,456][123
我主要使用Ruby来执行此操作,但到目前为止我的攻击计划如下:使用gemsrdf、rdf-rdfa和rdf-microdata或mida来解析给定任何URI的数据。我认为最好映射到像schema.org这样的统一模式,例如使用这个yaml文件,它试图描述数据词汇表和opengraph到schema.org之间的转换:#SchemaXtoschema.orgconversion#data-vocabularyDV:name:namestreet-address:streetAddressregion:addressRegionlocality:addressLocalityphoto:i
当我在Rails控制台中按向上或向左箭头时,出现此错误:irb(main):001:0>/Users/me/.rvm/gems/ruby-2.0.0-p247/gems/rb-readline-0.4.2/lib/rbreadline.rb:4269:in`blockin_rl_dispatch_subseq':invalidbytesequenceinUTF-8(ArgumentError)我使用rvm来管理我的ruby安装。我正在使用=>ruby-2.0.0-p247[x86_64]我使用bundle来管理我的gem,并且我有rb-readline(0.4.2)(人们推荐的最少
我可以得到Infinity和NaNn=9.0/0#=>Infinityn.class#=>Floatm=0/0.0#=>NaNm.class#=>Float但是当我想直接访问Infinity或NaN时:Infinity#=>uninitializedconstantInfinity(NameError)NaN#=>uninitializedconstantNaN(NameError)什么是Infinity和NaN?它们是对象、关键字还是其他东西? 最佳答案 您看到打印为Infinity和NaN的只是Float类的两个特殊实例的字符串
我不确定传递给方法的对象的类型是否正确。我可能会将一个字符串传递给一个只能处理整数的函数。某种运行时保证怎么样?我看不到比以下更好的选择:defsomeFixNumMangler(input)raise"wrongtype:integerrequired"unlessinput.class==FixNumother_stuffend有更好的选择吗? 最佳答案 使用Kernel#Integer在使用之前转换输入的方法。当无法以任何合理的方式将输入转换为整数时,它将引发ArgumentError。defmy_method(number)
我正在使用Ruby2.1.1和Rails4.1.0.rc1。当执行railsc时,它被锁定了。使用Ctrl-C停止,我得到以下错误日志:~/.rvm/gems/ruby-2.1.1/gems/spring-1.1.2/lib/spring/client/run.rb:47:in`gets':Interruptfrom~/.rvm/gems/ruby-2.1.1/gems/spring-1.1.2/lib/spring/client/run.rb:47:in`verify_server_version'from~/.rvm/gems/ruby-2.1.1/gems/spring-1.1.
当我的预订模型通过rake任务在状态机上转换时,我试图找出如何跳过对ActiveRecord对象的特定实例的验证。我想在reservation.close时跳过所有验证!叫做。希望调用reservation.close!(:validate=>false)之类的东西。仅供引用,我们正在使用https://github.com/pluginaweek/state_machine用于状态机。这是我的预订模型的示例。classReservation["requested","negotiating","approved"])}state_machine:initial=>'requested
我将我的Rails应用程序部署到OpenShift,它运行良好,但我无法在生产服务器上运行“Rails控制台”。它给了我这个错误。我该如何解决这个问题?我尝试更新rubygems,但它也给出了权限被拒绝的错误,我也无法做到。railsc错误:Warning:You'reusingRubygems1.8.24withSpring.UpgradetoatleastRubygems2.1.0andrun`gempristine--all`forbetterstartupperformance./opt/rh/ruby193/root/usr/share/rubygems/rubygems
我有这个html标记:我想得到这个:我如何使用Nokogiri做到这一点? 最佳答案 require'nokogiri'doc=Nokogiri::HTML('')您可以通过xpath删除所有属性:doc.xpath('//@*').remove或者,如果您需要做一些更复杂的事情,有时使用以下方法遍历所有元素会更容易:doc.traversedo|node|node.keys.eachdo|attribute|node.deleteattributeendend 关于ruby-Nokog