Complete the code to declare a reference to an integer.
let x = 10; let r = &[1];
The reference must point to a valid variable, so &x is correct.
Complete the code to return a reference to the first element of a slice safely.
fn first_element(slice: &[i32]) -> &i32 {
&slice[1]0
}To access the first element of a slice, use square brackets with index 0: slice[0].
Fix the error in the code to avoid returning a dangling reference.
fn get_str() -> &str {
let s = String::from("hello");
&[1]
}Returning &s or s.as_str() creates a dangling reference because s does not live long enough after the function returns. Return a reference to the string literal "hello", which has a 'static lifetime.
Fill both blanks to create a function that returns the longer of two string slices safely.
fn longest<'a>(x: &'a str, y: &'a str) -> &'a str { if [1] > y.len() { [2] } else { y } }
The function compares the lengths of x and y. The condition must be x.len() > y.len(). If true, return x, else return y.
Fill all three blanks to create a struct with a reference and implement a method returning that reference.
struct ImportantExcerpt<'a> { part: &'a str, } impl<'a> ImportantExcerpt<'a> { fn level(&self) -> i32 { [1] } fn announce_and_return_part(&self, announcement: &str) -> &[2] { println!("Announcement: {}", announcement); [3] } }
The level method returns an integer, here 3. The announce_and_return_part method returns a string slice &str and returns self.part, which is a reference to a string slice.
