Type Casting to String

Hi all!

I wonder that tarit member type casting. I want to cast to String to rustc_span::span member.
Is there any way to cast rustc_span::span to String Type or to cast String type regardless of any type?

Thank you!
Have a nice day :slight_smile:

A rustc_span is a "span", that is it only holds byte offsets (effectively). A String is an owned byte buffer, where the byte buffer must constitute a valid UTF-8 string. You can construct a String by copying the underlying data pointed to by the span into a buffer and making the String from that. Alternatively, you can also create &str (string slice) from the underlying data.
But you cannot by definition "cast" or convert a rustc_span into a String because the span doesn't contain any data.


Thank you for your comment!!

Then, How do I write code to store the data in rustc_span::span to a variable of type utf-8 string?

thank you!

You can use SourceMap::span_to_snippet. Note that this can fail when for example the source code is not available or when the start and end of the span are from different files. To get the SourceMap you can use the source_map() method on Session.