
作者最近尝试写了一些Rust代码,本文主要讲述了对Rust的看法和Rust与C++的一些区别。
背景
C++代码中的风险

其他不多展开。
Rust初体验
默认不可变
let x = 0;
x = 10; // error
let mut y = 0;
y = 10; //ok
fn foo(x: u32) {}
let x: i32 = 0;
foo(x); // error
简化构造、复制与析构
class ABC
{
public:
virtual ~ABC();
ABC(const ABC&) = delete;
ABC(ABC&&) = delete;
ABC& operator=(const ABC&) = delete;
ABC& operator=(ABC&&) = delete;
};
明明是一件非常常规的东西,写起来却那么的复杂。
fn main()
{
// String类似std::string,只支持显式clone,不支持隐式copy
let s: String = "str".to_string();
foo(s); // s will move
// cannot use s anymore
let y = "str".to_string();
foo(y.clone());
// use y is okay here
}
fn foo(s: String) {}
// can only be passed by move
struct Abc1
{
elems: Vec<int>
}
// can use abc.clone() to explicit clone a new Abc
#[derive(Clone)]
struct Abc2
{
elems: Vec<int>
}
// implement custom destructor for Abc
impl Drop for Abc2 {
// ...
}
// foo(xyz) will copy, 不能再定义Drop/析构函数,因为copy和drop是互斥的
#[dervie(Clone, Copy)]
struct Xyz
{
elems: i32
}
显式参数传递
let mut x = 10;
foo(x); // pass by move, x cannot be used after the call
foo(&x); // pass by immutable reference
foo(&mut x); // pass by mutable reference
看,连标准库自己都这样。std::filesystem,所有接口都有至少两个重载,一个抛异常,一直传std::error_code。
enum MyError
{
NotFound,
DataCorrupt,
Forbidden,
Io(std::io::Error)
}
impl From<io::Error> for MyError {
fn from(e: io::Error) -> MyError {
MyError::Io(e)
}
}
pub type Result<T> = result::Result<T, Error>;
fn main() -> Result<()>
{
let x: i32 = foo()?;
let y: i32 = bar(x)?;
foo(); // result is not handled, compile error
// use x and y
}
fn foo() -> Result<i32>
{
if (rand() > 0) {
Ok(1)
} else {
Err(MyError::Forbidden)
}
}
错误处理一律通过Result<T, ErrorType>来完成,通过?,一键向上传播错误(如同时支持自动从ErrorType1向ErrorType2转换,前提是你实现了相关trait),没有错误时,自动解包。当忘记处理处理Result时,编译器会报错。
内置格式化与lint
标准化的开发流程和包管理
cargo test
cargo bench
cargo规定了目录风格
benches // benchmark代码go here
src
tests // ut go here
Rust在安全性的改进
lifetime安全性
let s = vec![1,2,3]; // s owns the Vec
foo(s); // the ownership is passed to foo, s cannot be used anymore
let x = vec![1,2,3];
let a1 = &x[0];
let a2 = &x[0]; // a1/a2 are both immutable ref to x
x.resize(10, 0); // error: x is already borrowed by a1 and a2
println!("{a1} {a2}");
这种unique ownership + borrow check的机制,能够有效的避免pointer/iterator invalidation bug以及aliasing所引发的性能问题。
let s: &String;
{
let x = String::new("abc");
s = &x;
}
println!("s is {}", s); // error, lifetime(s) > lifetime(x)
这个例子比较简单,再看一些复杂的。
// not valid rust, for exposition only
struct ABC
{
x: &String,
}
fn foo(x: String)
{
let z = ABC { x: &x };
consume_string(x); // not compile, x is borrowed by z
drop(z); // call destructor explicitly
consume_string(x); // ok
// won't compile, bind a temp to z.x
let z = ABC { x: &String::new("abc") };
// use z
// Box::new == make_unique
// won't compile, the box object is destroyed soon
let z = ABC{ x: &*Box::new(String::new("abc") };
// use z
}
再看一个更加复杂的,涉及到多线程的。
void foo(ThreadPool* thread_pool)
{
Latch latch{2};
thread_pool->spawn([&latch] {
// ...
latch.wait(); // dangle pointer访问
});
// forget latch.wait();
}
这是一个非常典型的lifetime错误,C++可能要到运行时才会发现问题,但是对于Rust,类似代码的编译是不通过的。因为latch是个栈变量,其lifetime非常短,而跨线程传递引用时,这个引用实际上会可能在任意时间被调用,其lifetime是整个进程生命周期,rust中为此lifetime起了一个专门的名字,叫'static。正如cpp core guidelines所说:CP.24: Think of a thread as a global container ,never save a pointer in a global container。
fn foo(thread_pool: &mut ThreadPool)
{
let latch = Arc::new(Latch::new(2));
let latch_copy = Arc::clone(&latch);
thread_pool.spawn(move || {
// the ownership of latch_copy is moved in
latch_copy.wait();
});
latch.wait();
}
再看一个具体一些例子,假设你在写一个文件reader,每次返回一行。为了降低开销,我们期望返回的这一行,直接引用parser内部所维护的buffer,从而避免copy。
FileLineReader reader(path);
std::string_view<char> line = reader.NextLine();
std::string_view<char> line2 = reader.NextLine();
// ops
std::cout << line;
let reader = FileReader::next(path);
let line = reader.next_line();
// won't compile, reader is borrowed to line, cannot mutate it now
let line2 = reader.next_line();
println!("{line}");
// &[u8] is std::span<byte>
fn foo() -> &[u8] {
let reader = FileReader::next(path);
let line = reader.next_line();
// won't compile, lifetime(line) > lifetime(reader)
return line;
}
总结来说,Rust定义了一套规则,按照此规则进行编码,绝对不会有lifetime的问题。当Rust编译器无法推导某个写法的正确性时,它会强制你使用引用计数来解决问题。
边界安全性
类型安全性
let i: i32;
if rand() < 10 {
i = 10;
}
println!("i is {}", i); // do not compile: i is not always initialized
Rust的多线程安全性
Send/Sync是两个标准库的Trait,标准库在定义它们时,为已有类型提供了对应实现或者禁止了对应实现。
看个例子:假设我实现了一个Counter对象,希望多个线程同时使用。为了解决所有权问题,需要使用Arc<Counter>,来传递此共享对象。但是,以下代码是编译不通过的。
struct Counter
{
counter: i32
}
fn main()
{
let counter = Arc::new(Counter{counter: 0});
let c = Arc::clone(&counter);
thread::spawn(move || {
c.counter += 1;
});
c.counter += 1;
}
因为,Arc会共享一个对象,为了保证borrow机制,访问Arc内部对象时,都只能获得不可变引用(borrow机制规定,要么一个可变引用,要么若干个不可变引用)。Arc的这条规则防止了data race的出现。
fn main()
{
let counter = Arc::new(RefCell::new(Counter{counter: 0}));
let c = Arc::clone(&counter);
thread::spawn(move || {
c.get_mut().counter += 1;
});
c.get_mut().counter += 1;
}
为啥?因为RefCell不是Sync,即不允许多线程访问。Arc只在内部类型为Sync时,才为Send。即,Arc<Cell<T>>不是Send,无法跨线程传递。
struct Counter
{
counter: i32
}
fn main()
{
let counter = Arc::new(Mutex::new(Counter{counter: 0}));
let c = Arc::clone(&counter);
thread::spawn(move || {
let mut x = c.lock().unwrap();
x.counter += 1;
});
}
Rust的性能
// for demo purpose
fn foo(tasks: Vec<Task>)
{
let latch = Arc::new(Latch::new(tasks.len() + 1));
for task in tasks {
let latch = Arc::clone(&latch);
thread_pool.submit(move || {
task.run();
latch.wait();
});
}
latch.wait();
}
这里,latch必须用Arc(即shared_ptr)。
C++和Rust都可以通过inline来消除函数调用引起的开销。但是C++面对指针别名时,基本上是无能为力的。C++对于指针别名的优化依赖strict aliasing rule,不过这个rule出了名的恶心,Linus也骂过几次。Linux代码中,会使用-fno-strict-aliasing来禁止这条规则的。
int foo(const int* x, int* y)
{
*y = *x + 1;
return *x;
}
rust版本
fn foo(x: &i32, y: &mut i32) -> i32
{
*y = *x + 1;
*x
}
对应的汇编如下:
# c++
__Z3fooPKiPi:
ldr w8, [x0]
add w8, w8, #1
str w8, [x1]
ldr w0, [x0]
ret
# rust
__ZN2rs3foo17h5a23c46033085ca0E:
ldr w0, [x0]
add w8, w0, #1
str w8, [x1]
ret
看出差别没?
感想
Relax and enjoy coding!
1、Cpp core guidelines: https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines
2、Chrome在安全方面的探索:https://docs.google.com/document/d/e/2PACX-1vRZr-HJcYmf2Y76DhewaiJOhRNpjGHCxliAQTBhFxzv1QTae9o8mhBmDl32CRIuaWZLt5kVeH9e9jXv/pub
3、NSA对C++的批评:https://www.theregister.com/2022/11/11/nsa_urges_orgs_to_use/
4、C++ Lifetime Profile: https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#SS-lifetime
5、C++ Safety Profile: https://open-std.org/JTC1/SC22/WG21/docs/papers/2023/p2816r0.pdf?file=p2816r0.pdf
6、Herb CppCon2022 Slide: https://github.com/CppCon/CppCon2022/blob/main/Presentations/CppCon-2022-Sutter.pdf
7、Rust所有权模型理解:https://limpet.net/mbrubeck/2019/02/07/rust-a-unique-perspective.html
我需要在客户计算机上运行Ruby应用程序。通常需要几天才能完成(复制大备份文件)。问题是如果启用sleep,它会中断应用程序。否则,计算机将持续运行数周,直到我下次访问为止。有什么方法可以防止执行期间休眠并让Windows在执行后休眠吗?欢迎任何疯狂的想法;-) 最佳答案 Here建议使用SetThreadExecutionStateWinAPI函数,使应用程序能够通知系统它正在使用中,从而防止系统在应用程序运行时进入休眠状态或关闭显示。像这样的东西:require'Win32API'ES_AWAYMODE_REQUIRED=0x0
Rackup通过Rack的默认处理程序成功运行任何Rack应用程序。例如:classRackAppdefcall(environment)['200',{'Content-Type'=>'text/html'},["Helloworld"]]endendrunRackApp.new但是当最后一行更改为使用Rack的内置CGI处理程序时,rackup给出“NoMethodErrorat/undefinedmethod`call'fornil:NilClass”:Rack::Handler::CGI.runRackApp.newRack的其他内置处理程序也提出了同样的反对意见。例如Rack
我想用ruby编写一个小的命令行实用程序并将其作为gem分发。我知道安装后,Guard、Sass和Thor等某些gem可以从命令行自行运行。为了让gem像二进制文件一样可用,我需要在我的gemspec中指定什么。 最佳答案 Gem::Specification.newdo|s|...s.executable='name_of_executable'...endhttp://docs.rubygems.org/read/chapter/20 关于ruby-在Ruby中编写命令行实用程序
我构建了两个需要相互通信和发送文件的Rails应用程序。例如,一个Rails应用程序会发送请求以查看其他应用程序数据库中的表。然后另一个应用程序将呈现该表的json并将其发回。我还希望一个应用程序将存储在其公共(public)目录中的文本文件发送到另一个应用程序的公共(public)目录。我从来没有做过这样的事情,所以我什至不知道从哪里开始。任何帮助,将不胜感激。谢谢! 最佳答案 无论Rails是什么,几乎所有Web应用程序都有您的要求,大多数现代Web应用程序都需要相互通信。但是有一个小小的理解需要你坚持下去,网站不应直接访问彼此
我尝试运行2.x应用程序。我使用rvm并为此应用程序设置其他版本的ruby:$rvmuseree-1.8.7-head我尝试运行服务器,然后出现很多错误:$script/serverNOTE:Gem.source_indexisdeprecated,useSpecification.Itwillberemovedonorafter2011-11-01.Gem.source_indexcalledfrom/Users/serg/rails_projects_terminal/work_proj/spohelp/config/../vendor/rails/railties/lib/r
刚入门rails,开始慢慢理解。有人可以解释或给我一些关于在application_controller中编码的好处或时间和原因的想法吗?有哪些用例。您如何为Rails应用程序使用应用程序Controller?我不想在那里放太多代码,因为据我了解,每个请求都会调用此Controller。这是真的? 最佳答案 ApplicationController实际上是您应用程序中的每个其他Controller都将从中继承的类(尽管这不是强制性的)。我同意不要用太多代码弄乱它并保持干净整洁的态度,尽管在某些情况下ApplicationContr
我是一个Rails初学者,但我想从我的RailsView(html.haml文件)中查看Ruby变量的内容。我试图在ruby中打印出变量(认为它会在终端中出现),但没有得到任何结果。有什么建议吗?我知道Rails调试器,但更喜欢使用inspect来打印我的变量。 最佳答案 您可以在View中使用puts方法将信息输出到服务器控制台。您应该能够在View中的任何位置使用Haml执行以下操作:-puts@my_variable.inspect 关于ruby-on-rails-如何在我的R
如何检查Ruby文件是否是通过“require”或“load”导入的,而不是简单地从命令行执行的?例如:foo.rb的内容:puts"Hello"bar.rb的内容require'foo'输出:$./foo.rbHello$./bar.rbHello基本上,我想调用bar.rb以不执行puts调用。 最佳答案 将foo.rb改为:if__FILE__==$0puts"Hello"end检查__FILE__-当前ruby文件的名称-与$0-正在运行的脚本的名称。 关于ruby-检查是否
是否可以在应用程序中包含的gem代码中知道应用程序的Rails文件系统根目录?这是gem来源的示例:moduleMyGemdefself.included(base)putsRails.root#returnnilendendActionController::Base.send:include,MyGem谢谢,抱歉我的英语不好 最佳答案 我发现解决类似问题的解决方案是使用railtie初始化程序包含我的模块。所以,在你的/lib/mygem/railtie.rbmoduleMyGemclassRailtie使用此代码,您的模块将在
前言作为一名程序员,自己的本质工作就是做程序开发,那么程序开发的时候最直接的体现就是代码,检验一个程序员技术水平的一个核心环节就是开发时候的代码能力。众所周知,程序开发的水平提升是一个循序渐进的过程,每一位程序员都是从“菜鸟”变成“大神”的,所以程序员在程序开发过程中的代码能力也是根据平时开发中的业务实践来积累和提升的。提高代码能力核心要素程序员要想提高自身代码能力,尤其是新晋程序员的代码能力有很大的提升空间的时候,需要针对性的去提高自己的代码能力。提高代码能力其实有几个比较关键的点,只要把握住这些方面,就能很好的、快速的提高自己的一部分代码能力。1、多去阅读开源项目,如有机会可以亲自参与开源