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:
    rust Copy
    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

What is the difference between Copy and Clone in Rust?

junior

What happens when you pass a String to a function in Rust?

middle

When can’t my type be Copy in Rust?

Bình luận

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

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