Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String slices in structs (in Rust) [duplicate]

How do I tell Rust that I want a struct which contains a slice of a string?

I've tried:

struct Welcome {
    version: &str,
}

but the compiler complains:

src/chat.rs:16:14: 16:18 error: missing lifetime specifier [E0106]
src/chat.rs:16     version: &str,

From my limited understanding of Rust, I think a string slice is a pointer+length into some text allocated elsewhere.

I want the lifetime of the string slice to be the life time of the allocated text.

like image 301
fadedbee Avatar asked Oct 14 '14 11:10

fadedbee


People also ask

Are strings mutable in Rust?

Rust owned String type, the string itself lives on the heap and therefore is mutable and can alter its size and contents.

How do you parse strings in Rust?

To convert a string to an integer in Rust, use parse() function. The parse function needs to know what type, which can be specified on the left-side of assignment like so: let str = "123"; let num: i32 = str. parse().

What is a string slice in Rust?

A string slice is a reference to part of a String , and it looks like this: let s = String::from("hello world"); let hello = &s[0.. 5]; let world = &s[6.. 11]; Rather than a reference to the entire String , hello is a reference to a portion of the String , specified in the extra [0..


1 Answers

Your understanding is mostly correct and you were just one step away from what you want. You can use a named lifetime in this way:

struct Welcome<'a> {
    version: &'a str,
}

This says that the &str reference must have the same lifetime as the containing Welcome struct. More info on lifetimes can be found in the lifetimes guide

like image 97
Paolo Falabella Avatar answered Sep 20 '22 07:09

Paolo Falabella