#Rust used as a pure functional language

9 messages · Page 1 of 1 (latest)

jolly parcel
#

Hello! I'm reading Rust book and currently has finished the part on memory management model and ownership/borrowing concepts. I don't have any experience with Rust but the whole approach to memory management made me curious: if memory is freed once the value is dropped (goes out of scope), would it be safe to say that if Rust is used in a pure functional way, one wouldn't have to worry about memory at all (or almost at all)?

Pure functional way here stands for immutability everywhere and no side-effects. Just functions which take values and produce other values.

The book gives this example:

fn main() {
    let s1 = String::from("hello");    // s2 comes into scope

    let s2 = takes_and_gives_back(s1); // s2 is moved into
                                       // takes_and_gives_back, which also
                                       // moves its return value into s3
} // Here, s3 goes out of scope and is dropped. s2 was moved, so nothing
  // happens. s1 goes out of scope and is dropped.

// This function takes a String and returns a String.
fn takes_and_gives_back(a_string: String) -> String {
    // a_string comes into
    // scope

    a_string  // a_string is returned and moves out to the calling function
}

This is a pure functional way - you have a string, then you pass it to another function, function doesn't mutate the original value, just returns a new value (here it returns the original string but this is copied from the book). You don't need the old value (and it's not available).

What are downsides if I program in Rust like this? Are there any edge cases where I would absolutely need borrowing, references and other memory stuff? What about performance?

Currently I know almost nothing about Rust but reading about this makes me think if used like purely functional lang (like Haskell) you get performance, speed security and all of this without GC!

lime flower
#

you'll probably also find it difficult to express certain kinds of long running, stateful services in a purely functional way (eg web services)

#

note that rust tends to shy away from eg linked lists for example in favour of dynamically reallocated arrays, as they generally have better characteristics in terms of cache locality and allocation overhead

lime flower
jolly parcel
lime flower
jolly parcel