Beginner question : api lookup question

I was looking at this piece of code

let s = String::deserialize(deserializer)?;

I was like; Oh ok! I didn't know there was a deserialize method on String.

Seeing how it called like this String::deserialize().

Was expecting to see deserialize` in the String struct api.

But I don't see it. Is it because String has too many traits to list out ?
Then I searched for serde in String, but nothing found there either.

What you're looking for is here. Searching for 'deserialize' on the serde crate gives serde::Deserialize as the top results, and you can see it is implemented for String down below (as well as a whole host of other types it is also implemented for.) In general, because Deserialize and String are both foreign types, the String impl of Deserialize must either be in std or in serde.

Ok thanks.

Can you plz elaborate on Foreign. what qualifies String as Foreign ? Sounds like a core struct to me.

And if they are not listed in std or serde. where else can they be ?

A foreign type is one that is not defined in your crate. If you're using std and serde as a library, all of the types in either of them are foreign. This is important because you cannot implement foreign traits on foreign types, which is what would have to happen if you wanted to provide your own impl Deserialize for String.

Ok got it:

  • you can implement your own traits on any type, meaning foreign too.
  • you can implement foreign traits on your own types.
  • But you can't implement foreign traits on foreign types.

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.