1

I saw this image while reading "the book" (https://doc.rust-lang.org/book/ch04-02-references-and-borrowing.html#references-and-borrowing):

reference representation in Rust

I have two questions:

  1. Does reference s point to s1 itself (address of struct s1) or the member ptr of s1?

  2. Is s (the reference) itself a Struct that contains a public member ptr or a pointer (string* s) like in C++?

For easier understanding:

fn main() {
    // String
    let s1 = String::from("hello");

    // reference
    let s = &s1;

    println!("s:{:p}, s1:{:p}", s, &s1);
    // OUTPUT: s:0x63373afae0, s1:0x63373afae0

}
5
  • 2
    Is this a visualization of let s = &s1 where let s1 = "hello".to_string()? Commented Jan 4, 2023 at 16:39
  • In Rust, references tend to behave like pointers but with all sorts of other checks, like borrow checking, no ability to create "null" references, etc. Commented Jan 4, 2023 at 16:40
  • 1
    Where did you see this picture? Commented Jan 4, 2023 at 16:47
  • You should include the context of how s and s1 are defined in their example. Commented Jan 4, 2023 at 16:49
  • @tadman I saw it in the Rust book, I have added the link, Thank you. Commented Jan 4, 2023 at 17:35

1 Answer 1

3

Does reference s point to s1 itself (address of struct s1) or the member ptr of s1?

It is pointing on the whole struct.

Is s (the reference) itself a Struct that contains a public member ptr or a pointer (string* s) like in C++?

A pointer; references are a primitive.

Sign up to request clarification or add additional context in comments.

7 Comments

"both have the same address" How can you be sure of this?
@E_net4thecommentflagger Because that's what the figure shows :) Not because I know the layout of String of course.
The figure merely shows a possible arrangement of fields within struct String. s and s1 are part of a code snippet. The way they are arranged and padded in memory is unspecified, so they might not always "have the same address".
@E_net4thecommentflagger Ok, got your opinion. Will edit.
But the Slice type is also a pointer, it should be a Struct, right? Because it has two public fileds: ptr and length: Struct fatPointer {pub ptr, pub length},
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.