Rust中的組合運營商和管道轉發運營商(like in other languages)是否都存在?如果是這樣,他們是什麼樣子,一個人應該比另一個更喜歡?如果不存在,爲什麼這個操作員不需要?Rust中的組合運營商和管道轉發運營商
18
A
回答
19
有內置的沒有這樣的運營商,但它不是特別難界定:
use std::ops::Shr;
struct Wrapped<T>(T);
impl<A, B, F> Shr<F> for Wrapped<A>
where F: FnOnce(A) -> B
{
type Output = Wrapped<B>;
fn shr(self, f: F) -> Wrapped<B> {
Wrapped(f(self.0))
}
}
fn main() {
let string = Wrapped(1) >> (|x| x + 1) >> (|x| 2 * x) >> (|x: i32| x.to_string());
println!("{}", string.0);
}
// prints `4`
的Wrapped
新型結構純粹是爲了讓Shr
實例,因爲否則我們就必須實現它在通用(即impl<A, B> Shr<...> for A
),並不起作用。
需要注意的是地道的鐵鏽會調用這個方法map
而不是使用運營商。有關典型示例,請參見Option::map
。
3
就我所知,這些操作符在Rust中不存在。到目前爲止,我還沒有對它們有太多的需求,並且還努力保持核心Rust語法相當小。例如,Rust曾經有明確的消息傳遞操作符,但是這些操作符被刪除了。
如果需要,您可能可以使用運算符重載來提供類似的內容,或者只編寫自己的組合或管道轉發函數。如果Rust團隊願意將這些包含在標準庫中,我不會感到驚訝。
-1
正如另一張海報所說,Rust中不存在這樣的操作符,並且可能不會被添加。您鏈接的頁面中描述的管道轉發運營商便於數據流動。爲此,Rust的方式是產生任務並使用數據通道在它們之間發送信息。
任務與其他語言的線程類似,儘管它們具有更多限制性(因此更安全)的內存共享規則。作爲一個例子,這是一個使用任務和端口/通道來促進兩個進程之間數據流動的防火牆程序。請注意 - 此代碼是針對0.6
extern mod std;
// Import the relevant pipes structs and the stream fn
use core::pipes::{stream, Port, Chan};
use std::comm::DuplexStream;
// This function shows the simplest case of using a
// channel and a pipe
fn pipes() {
// Create a new stream
let (port, chan): (Port<int>, Chan<int>) = stream();
// Spawn off a task to send '10' through the channel
do spawn { chan.send(10); }
// The recv call will block until data is present
println(int::to_str(port.recv()));
}
// This function will serve as the logic for the
// data flow task below
fn plus_one(channel: &DuplexStream<int, int>) {
let mut value: int;
// Add one and send back the result until 0 is encountered
loop {
value = channel.recv();
channel.send(value + 1);
if value == 0 { break; }
}
}
fn main() {
// DuplexStream, as the name implies, allows bidirectional
// information flow
let (from_child, to_child) = DuplexStream();
do spawn { plus_one(&to_child); };
from_child.send(22);
from_child.send(23);
from_child.send(24);
from_child.send(25);
from_child.send(0);
for 4.times {
let answer = from_child.recv();
println(int::to_str(answer));
}
}
這個概念版本編譯可以擴展到任何模型數據流,你需要你的程序來執行。根據Actor Model重新概念化您的問題可能會有所幫助。最後,你的語言進行工作,也有一些,我會建議在網絡上真正有用的資源,您諮詢:上irc.mozilla.org
希望這會有所幫助,歡迎來到Rust社區!
相關問題
- 1. 空 - 結合運營商和運營商&&
- 2. &&和||運營商
- 3. 運營商的情況下運營商
- 4. 的JavaScript +運營商VS - 運營商
- 5. 結合&和*運營商
- 6. 或運營商與三元運營商
- 7. 轉換運營商和運營商>>
- 8. 同一組中運營商的C運營商優先級
- 9. 實施管道運營商的成本
- 10. C#| =和&=運營商
- 11. ==和eq運營商
- 12. QSharedData和運營商=
- 13. PHP!=和==運營商
- 14. C++和++運營商
- 15. REGEXP和運營商。+
- 16. 停止管道運營商鏈
- 17. 紅寶石管道運營商
- 18. 運營商在託管C++
- 19. Javascript:?運營商
- 20. R%*%運營商
- 21. instanceof運營商
- 22. Bigint +運營商
- 23. Groovy *。運營商
- 24. '運營商='
- 25. jQuery @運營商?
- 26. ??運營商system.DBNull
- 27. 運營商
- 28. 令運營商
- 29. &&運營商JSONpath()
- 30. Javascript +運營商
這很美! –
每個步驟的括號是否必需?我不太確定這裏的操作順序是什麼。什麼是「Shr」?這是你如何超載「右移」運營商?我們可以定義一個不同的嗎?說'|>'? – mpen
@Mark no,你不能定義新的操作符,並且是的,括號是必要的,因爲閉包儘可能地解析它的身體,例如, '| X&| x + 1 >> |&x | 2 * x'將被解析爲'|&x | x +(1 >>(| x | 2 * x))'並且右移一個閉包根本沒有任何意義(並且如預期的那樣,不檢查類型)。 – huon