I know that a String
mainly consists of a pointer that contains the address to its allocated place in the heap memory. Rust prohibits any copies of String
s to avoid double free errors, so it introduced borrowing, where the code basically only copies the pointer value without copying the value in the heap.
However, integer types are stored in the stack and hence do not have a pointer. Yet it is still possible to create a reference to an integer:
let i: i64 = 42;
let j = &i;
Since an integer contains no reference to the heap, isn't a borrowed integer simply a regular copy of it? E.g. is there any difference between j = i
and j = &i
?
Consider the case if the reference were mutable:
let mut i: u64 = 42;
let j = &mut i;
*j = 5;
println!("{}", i);
5
It should be obvious from this demonstration that j
is not simply a copy. It does reference and therefore modify the original i
.
Integer types are stored in the stack and hence do not have a pointer.
Not sure where you got that idea from. If it exists in memory, then it has an address within that memory, and therefore you can have a pointer (or reference) that points to it. The properties of a u64
do not change depending on where it is.
The comparison to strings may be tripping you up:
let s = String::from("hello world");
let s_ref: &String = &s;
let str_ref: &str = s.as_str();
If you have a String
variable s
, and take a reference to it, s_ref
, it does not point directly to the heap, it points to the variable s
on the stack. There is a slice-type str
that represents a region of utf8-encoded bytes, which a String
holds on the heap. You can get a reference to that region of memory directly on the heap by getting it via .as_str()
/.as_ref()
or by converting the &String
into a &str
via deref coercion.
But in the case of u64
vs &u64
, there isn't much of a practical difference between the two except the latter incurs an extra level of indirection in the generated code and you may have to worry about lifetime constraints. Because of that, its usually better to use copies of integer types if given the choice. You'd still see references to integers though if using them through some generic interface.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments