同样是async await,rust和js的运行机制是一样的吗?

nodejs es7后开始支持async/await语法,原理是,当js引擎运行到io时,像异步代码一样切换到其他代码栈运行,当io完成后再运行await后面的代码,本质上是单线程的。
今天我看到rust语言也有这个语法,是一种无栈协程,但rust没有单线程的限制,那rust这个语法的运行原理跟node js是不是不太一样?

阅读 2k
1 个回答
Rust 与 nodejs async 运行原理一样不一样不肯定, 因为没有看过Rust,nodejs,async的runtime所以不敢肯定,下面是Async Rust一些情况

Language and library support

While asynchronous programming is supported by Rust itself, most async applications depend on functionality provided by community crates. As such, you need to rely on a mixture of language features and library support:

  • The most fundamental traits, types and functions, such as the Future trait are provided by the standard library.
  • The async/await syntax is supported directly by the Rust compiler.
  • Many utility types, macros and functions are provided by the futures crate. They can be used in any async Rust application.
  • Execution of async code, IO and task spawning are provided by "async runtimes", such as Tokio and async-std. Most async applications, and some async crates, depend on a specific runtime.

crates 相当于 npm中的packages;traits是接口的意思,相当于golang中的interface;

Rust语言本身定义了一些关于async的一些类型,函数,接口,比如 async,await这些关键子属于语言本身,但是 rust 并没有实现 async runtime;runtime 是由社区的 Tokio 以及std 中的async-std 实现的。

Refs:

State of async rust
Meet async/await in Swift

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题