Help: Cloning string in the getter

So i'm creating a very simple structure that i need to extract the string value later, i'm using wasm_bindgen with javascript, so these values need to be read in javascript later

pub struct Text {
    value: String,
    x: u32,
    y: u32,

i'm creating a getter to get the string value

impl Text {
    pub fn value(&self) -> String {

But i don't understand why do i need to use clone in this getter, why can't I just do


also, what exactly into() does ?

Any help is appreciated! Thanks :slight_smile:

Welcome. First off, please read the pinned post about code formatting.

into() is a method provided by the trait Into (which is strongly coupled to the trait From). In the contexts of Strings, it is most useful for its ability to convert &str into a String (by cloning the contents of the &str).

For your getter however, the way you use it, you can just drop the into() as it actually doing nothing here.

Also, you should probably change the type signature to -> &str. Then your implementation can just do { &self.value }. The reason why clone() is required with the type signature you have is that String is an owned string which cannot be shared, so it needs to be cloned to get something to return from the fn value while also retaining the String in the field.

1 Like

Thanks a lot @steffahn , I'm just starting out with rust, sorry for the unformated post, gonna change it

.into() doesn't do anything here. It "converts" String to String.

1 Like

One more but of info when you read the description of Into (which is unfortunately hidden by default on the docs page):

pub trait Into<T> {
    fn into(self) -> T;

A most crucial detail that is easy for beginners to overlook is that it takes a self with no reference (rather than a & self or &mut self). This means that when you call this method it consumes the object it is called on. In your code, this means that you can't use .into() directly on your data field except if you're willing to sacrifice the entire struct. In contrast, clone takes a & self and is this safe to call.


This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.