本文簡要介紹rust語言中 Trait std::ops::Generator
的用法。
用法
pub trait Generator<R = ()> {
type Yield;
type Return;
fn resume( self: Pin<&mut Self>, arg: R ) -> GeneratorState<Self::Yield, Self::Return>;
}
由內置生成器類型實現的特征。
生成器(通常也稱為協程)目前是 Rust 中的一項實驗性語言函數。在 RFC 2033 中添加的生成器目前主要旨在為 async/await 語法提供構建塊,但可能會擴展到為迭代器和其他原語提供符合人體工程學的定義。
生成器的語法和語義不穩定,需要進一步的 RFC 來穩定。不過,此時的語法是closure-like:
#![feature(generators, generator_trait)]
use std::ops::{Generator, GeneratorState};
use std::pin::Pin;
fn main() {
let mut generator = || {
yield 1;
return "foo"
};
match Pin::new(&mut generator).resume(()) {
GeneratorState::Yielded(1) => {}
_ => panic!("unexpected return from resume"),
}
match Pin::new(&mut generator).resume(()) {
GeneratorState::Complete("foo") => {}
_ => panic!("unexpected return from resume"),
}
}
更多關於生成器的文檔可以在不穩定的書中找到。
相關用法
- Rust GlobalAlloc用法及代碼示例
- Rust UdpSocket.set_multicast_loop_v6用法及代碼示例
- Rust i64.overflowing_add_unsigned用法及代碼示例
- Rust Box.downcast用法及代碼示例
- Rust BTreeMap.last_key_value用法及代碼示例
- Rust str.make_ascii_uppercase用法及代碼示例
- Rust u128.checked_pow用法及代碼示例
- Rust usize.wrapping_mul用法及代碼示例
- Rust AtomicU8.fetch_sub用法及代碼示例
- Rust PanicInfo.payload用法及代碼示例
- Rust MaybeUninit.assume_init_mut用法及代碼示例
- Rust String.try_reserve用法及代碼示例
- Rust Mutex.new用法及代碼示例
- Rust f32.exp用法及代碼示例
- Rust Result.unwrap_or_else用法及代碼示例
- Rust slice.sort_unstable_by_key用法及代碼示例
- Rust Formatter.precision用法及代碼示例
- Rust i128.log2用法及代碼示例
- Rust OsStr.to_ascii_uppercase用法及代碼示例
- Rust f32.hypot用法及代碼示例
- Rust RefCell.try_borrow_unguarded用法及代碼示例
- Rust i16.log10用法及代碼示例
- Rust LowerExp用法及代碼示例
- Rust HashSet.get_or_insert_with用法及代碼示例
- Rust Bound.cloned用法及代碼示例
注:本文由純淨天空篩選整理自rust-lang.org大神的英文原創作品 Trait std::ops::Generator。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。