Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Rust doesn't have pass-by-reference in the sense that C# or C++ do. The `&` and `&mut` types are called references[1], but what is meant by "reference" is the C++ guarantee that a reference always points to a valid value. This C++ code uses references without explicit pointer deferencing:

    #include <iostream>
    #include <string>
    
    void s_ref_modify(std::string& s)
    {
        s = std::string("Best");
        return;
    }
    
    int main()
    {
        std::string str = "Test";
        s_ref_modify(str);
        std::cout << str << '\n';
    }
The equivalent Rust requires passing a mutable pointer to the callee, where it is explicitly dereferenced:

    fn s_ref_modify(s: &mut String) {
        *s = String::from("Best");
    }
    
    fn main() {
        let mut str = String::from("Test");
        s_ref_modify(&mut str);
        println!("{}", str);
    }
Swift has `inout` parameters, which superficially look similar to pass-by-reference, except that the semantics are actually copy-in copy-out[2]:

> In-out parameters are passed as follows:

> 1. When the function is called, the value of the argument is copied.

> 2. In the body of the function, the copy is modified.

> 3. When the function returns, the copy’s value is assigned to the original argument.

> This behavior is known as _copy-in copy-out_ or _call by value result_. For example, when a computed property or a property with observers is passed as an in-out parameter, its getter is called as part of the function call and its setter is called as part of the function return.

[1]: https://doc.rust-lang.org/book/ch04-02-references-and-borrow...

[2]: https://docs.swift.org/swift-book/documentation/the-swift-pr....



Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: