When we say slice or slice type, it's &v[t] or v[t]? What we say trait or trai type, it's trait or &trait?
The official book says slice type is &v[t], but error doc says " in a slice type like [u32]
".
It's really confusing.
When we say slice or slice type, it's &v[t] or v[t]? What we say trait or trai type, it's trait or &trait?
The official book says slice type is &v[t], but error doc says " in a slice type like [u32]
".
It's really confusing.
[T]
is a slice.&[T]
is a reference to a slice, but it's often called just a slice, since there's not much you can do with a slice without some indirection.dyn Trait
is called a trait object. It is a proper type.&dyn Trait
and Box<dyn Trait>
being called a trait object.Thanks @H2CO3. It's difficult for me to print the result of unsafe.sizeof. I would appreciate if you could share more insight into my questions below:
In 32bit machine,
let a = [1, 2, 3, 4, 5];
let s = &a[1..3];
the size of s is 4 or 4*2=8? '&' on the right side makes me think s is a pointer. But if the size if 12, then it makes me think s is a "slice object".
Similar questions for the TYPE "trait object",
let person = Person;
let interface = person as &Interface;
Is the size of interface 4 or 4 * 2?
I got the answers from the doc below:
Pointer types to DSTs are sized but have twice the size of pointers to sized types
- Pointers to slices also store the number of elements of the slice.
- Pointers to trait objects also store a pointer to a vtable.
So they are the rust "pointer" types, but the sizes are 8. Actually we cannot use the two types "slice" and "trait object" directly in our code.
Please correct me if I am wrong.
I don't understand what is being asked here.
&[T]
and &dyn Trait
(and other, smart pointer types to them, like Box<[T]>
) are fat pointers, they always have size_of::<&[T]>() == 2 * size_of::<usize>()
.
let x = [1, 2, 3, 4]
is an array, not a slice (it's [i32; 4]
, not [i32]
). It is therefore sized, with a size of 4 * size_of::<i32>()
. A reference to it has a size of one usize (machine word). You can convert it to a reference to a slice, though.
Similarly, all other pointers to sized values have size size_of::<usize>()
.
Thanks. The "fat pointers" make me clear about those concepts.
This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.