Câu hỏi phỏng vấn Rust
Câu hỏi

What's the difference between self and Self in Rust?

Câu trả lời

In Rust, self and Self serve different purposes and are used in different contexts within the language.

self

  • Instance Reference: self is used as the first parameter in method definitions to refer to the instance of the struct or enum on which the method is being called. It is analogous to this in other object-oriented languages like JavaScript or Python.
  • Ownership and Borrowing: When used in method signatures, self can take different forms to indicate ownership and borrowing:
    • self: Takes ownership of the instance.
    • &self: Borrows the instance immutably.
    • &mut self: Borrows the instance mutably.
  • Example:
    struct MyType;
    
    impl MyType {
        fn consume(self) {
            // Takes ownership of the instance
        }
    
        fn borrow(&self) {
            // Borrows the instance immutably
        }
    
        fn borrow_mut(&mut self) {
            // Borrows the instance mutably
        }
    }

Self

  • Type Alias: Self is a type alias for the type that is currently being implemented. It is used within impl blocks and trait definitions to refer to the type for which the methods...
middle

middle

Gợi ý câu hỏi phỏng vấn

middle

How would you model a Many-to-Many relationship with a Reference-Counted Smart Pointer in Rust?

junior

What is a Borrow Checker in Rust?

junior

What is the Option type in Rust, and why is it useful?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào