What is a fat pointer?
A fat pointer not only points to a particular address, but also stores some information about it, such as the size of the data structure.
In Rust, fat pointers are frequently used to represent slices, which are contiguous sequences of memory elements. A slice fat pointer stores a pointer to the slice's beginning element and length. This information can be used to perform boundary checks and avoid memory problems.
Code example
Let's take a look at a coding implementation to get a better understanding.
struct StrPtr {ptr: *const u8,len: usize,}fn main() {let s1 = String::from("I like learning from Educative Answers");let ptr = s1.as_ptr();let len = s1.len();let fatptr = StrPtr { ptr, len };unsafe {let slice = std::slice::from_raw_parts(fatptr.ptr, fatptr.len);let str = std::str::from_utf8_unchecked(slice);println!("{}", str);}}
Code explanation
Let’s understand how the code above works:
Lines 1–4: We define a
structwith the name ofStrPtrto create a fat pointer that stores both the address and length of the pointed value.Lines 7–10: We create an object and store its pointer and length in two variables, and then combine them into a
StrPtrstructto create a fat pointer.Lines 11–15: Using the
unsafeblock, we make aslicefrom a fat pointer representing a string. It then usesstd::str::from_utf8_uncheckedto convert the slice to a string, assuming the data is valid by the UTF-8 standard and has no runtime checks. To output the generated string, we useprintln!.
Free Resources