2013-06-11 156 views

回答

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

+0

這很美! –

+0

每個步驟的括號是否必需?我不太確定這裏的操作順序是什麼。什麼是「Shr」?這是你如何超載「右移」運營商?我們可以定義一個不同的嗎?說'|>'? – mpen

+0

@Mark no,你不能定義新的操作符,並且是的,括號是必要的,因爲閉包儘可能地解析它的身體,例如, '| X&| x + 1 >> |&x | 2 * x'將被解析爲'|&x | x +(1 >>(| x | 2 * x))'並且右移一個閉包根本沒有任何意義(並且如預期的那樣,不檢查類型)。 – huon

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

  1. Official Docs
  2. Rust for Rubyists
  3. #rust

希望這會有所幫助,歡迎來到Rust社區!