Borrowing inside a struct

⚓ rust    📅 2025-05-19    👤 surdeus    👁️ 5      

surdeus

Warning

This post was published 42 days ago. The information described in this article may have changed.

Info

This post is auto-generated from RSS feed The Rust Programming Language Forum - Latest topics. Source: Borrowing inside a struct

Hi there,
I'm new to rust. I'm currently working on one of my first few projects in getting used to the language.

For my current project I'm trying to implement a struct that contains a String and a list of fat pointers into that string (Vec<&str>). Intuitively, this seems reasonable and possible since the struct should own both the original String and the pointers to it, therefore making sure that the referenced values live as long as the entire struct does.

Is it actually possible? If so: How do I get the rust compiler to accept this structure?
My current attempt fails because the I can't move the String after borrowing:

struct SelfReferenced {
  src: String,
  links: Vec<&str>,
}

impl SelfReferenced {
  fn build(src: String) -> Self {
    Spec {
      src,
      links: vec![src.as_str()],
    }
  }
}

2 posts - 1 participant

Read full topic

🏷️ rust_feed