Skip to main content

String

Struct String 

1.0.0 · Source
pub struct String { /* private fields */ }
Expand description

A UTF-8–encoded, growable string.

String is the most common string type. It has ownership over the contents of the string, stored in a heap-allocated buffer (see Representation). It is closely related to its borrowed counterpart, the primitive str.

§Examples

You can create a String from a literal string with String::from:

let hello = String::from("Hello, world!");

You can append a char to a String with the push method, and append a &str with the push_str method:

let mut hello = String::from("Hello, ");

hello.push('w');
hello.push_str("orld!");

If you have a vector of UTF-8 bytes, you can create a String from it with the from_utf8 method:

// some bytes, in a vector
let sparkle_heart = vec![240, 159, 146, 150];

// We know these bytes are valid, so we'll use `unwrap()`.
let sparkle_heart = String::from_utf8(sparkle_heart).unwrap();

assert_eq!("💖", sparkle_heart);

§UTF-8

Strings are always valid UTF-8. If you need a non-UTF-8 string, consider OsString. It is similar, but without the UTF-8 constraint. Because UTF-8 is a variable width encoding, Strings are typically smaller than an array of the same chars:

// `s` is ASCII which represents each `char` as one byte
let s = "hello";
assert_eq!(s.len(), 5);

// A `char` array with the same contents would be longer because
// every `char` is four bytes
let s = ['h', 'e', 'l', 'l', 'o'];
let size: usize = s.into_iter().map(|c| size_of_val(&c)).sum();
assert_eq!(size, 20);

// However, for non-ASCII strings, the difference will be smaller
// and sometimes they are the same
let s = "💖💖💖💖💖";
assert_eq!(s.len(), 20);

let s = ['💖', '💖', '💖', '💖', '💖'];
let size: usize = s.into_iter().map(|c| size_of_val(&c)).sum();
assert_eq!(size, 20);

This raises interesting questions as to how s[i] should work. What should i be here? Several options include byte indices and char indices but, because of UTF-8 encoding, only byte indices would provide constant time indexing. Getting the ith char, for example, is available using chars:

let s = "hello";
let third_character = s.chars().nth(2);
assert_eq!(third_character, Some('l'));

let s = "💖💖💖💖💖";
let third_character = s.chars().nth(2);
assert_eq!(third_character, Some('💖'));

Next, what should s[i] return? Because indexing returns a reference to underlying data it could be &u8, &[u8], or something similar. Since we’re only providing one index, &u8 makes the most sense but that might not be what the user expects and can be explicitly achieved with as_bytes():

// The first byte is 104 - the byte value of `'h'`
let s = "hello";
assert_eq!(s.as_bytes()[0], 104);
// or
assert_eq!(s.as_bytes()[0], b'h');

// The first byte is 240 which isn't obviously useful
let s = "💖💖💖💖💖";
assert_eq!(s.as_bytes()[0], 240);

Due to these ambiguities/restrictions, indexing with a usize is simply forbidden:

let s = "hello";

// The following will not compile!
println!("The first letter of s is {}", s[0]);

It is more clear, however, how &s[i..j] should work (that is, indexing with a range). It should accept byte indices (to be constant-time) and return a &str which is UTF-8 encoded. This is also called “string slicing”. Note this will panic if the byte indices provided are not character boundaries - see is_char_boundary for more details. See the implementations for SliceIndex<str> for more details on string slicing. For a non-panicking version of string slicing, see get.

The bytes and chars methods return iterators over the bytes and codepoints of the string, respectively. To iterate over codepoints along with byte indices, use char_indices.

§Deref

String implements Deref<Target = str>, and so inherits all of str’s methods. In addition, this means that you can pass a String to a function which takes a &str by using an ampersand (&):

fn takes_str(s: &str) { }

let s = String::from("Hello");

takes_str(&s);

This will create a &str from the String and pass it in. This conversion is very inexpensive, and so generally, functions will accept &strs as arguments unless they need a String for some specific reason.

In certain cases Rust doesn’t have enough information to make this conversion, known as Deref coercion. In the following example a string slice &'a str implements the trait TraitExample, and the function example_func takes anything that implements the trait. In this case Rust would need to make two implicit conversions, which Rust doesn’t have the means to do. For that reason, the following example will not compile.

trait TraitExample {}

impl<'a> TraitExample for &'a str {}

fn example_func<A: TraitExample>(example_arg: A) {}

let example_string = String::from("example_string");
example_func(&example_string);

There are two options that would work instead. The first would be to change the line example_func(&example_string); to example_func(example_string.as_str());, using the method as_str() to explicitly extract the string slice containing the string. The second way changes example_func(&example_string); to example_func(&*example_string);. In this case we are dereferencing a String to a str, then referencing the str back to &str. The second way is more idiomatic, however both work to do the conversion explicitly rather than relying on the implicit conversion.

§Representation

A String is made up of three components: a pointer to some bytes, a length, and a capacity. The pointer points to the internal buffer which String uses to store its data. The length is the number of bytes currently stored in the buffer, and the capacity is the size of the buffer in bytes. As such, the length will always be less than or equal to the capacity.

This buffer is always stored on the heap.

You can look at these with the as_ptr, len, and capacity methods:

let story = String::from("Once upon a time...");

// Deconstruct the String into parts.
let (ptr, len, capacity) = story.into_raw_parts();

// story has nineteen bytes
assert_eq!(19, len);

// We can re-build a String out of ptr, len, and capacity. This is all
// unsafe because we are responsible for making sure the components are
// valid:
let s = unsafe { String::from_raw_parts(ptr, len, capacity) } ;

assert_eq!(String::from("Once upon a time..."), s);

If a String has enough capacity, adding elements to it will not re-allocate. For example, consider this program:

let mut s = String::new();

println!("{}", s.capacity());

for _ in 0..5 {
    s.push_str("hello");
    println!("{}", s.capacity());
}

This will output the following:

0
8
16
16
32
32

At first, we have no memory allocated at all, but as we append to the string, it increases its capacity appropriately. If we instead use the with_capacity method to allocate the correct capacity initially:

let mut s = String::with_capacity(25);

println!("{}", s.capacity());

for _ in 0..5 {
    s.push_str("hello");
    println!("{}", s.capacity());
}

We end up with a different output:

25
25
25
25
25
25

Here, there’s no need to allocate more memory inside the loop.

Implementations§

Source§

impl String

1.0.0 (const: 1.39.0) · Source

pub const fn new() -> String

Creates a new empty String.

Given that the String is empty, this will not allocate any initial buffer. While that means that this initial operation is very inexpensive, it may cause excessive allocation later when you add data. If you have an idea of how much data the String will hold, consider the with_capacity method to prevent excessive re-allocation.

§Examples
let s = String::new();
Examples found in repository?
examples/app/custom_loop.rs (line 45)
43fn main() -> AppExit {
44    App::new()
45        .insert_resource(Input(String::new()))
46        .set_runner(my_runner)
47        .add_systems(Update, (print_system, exit_system))
48        .run()
49}
More examples
Hide additional examples
examples/3d/light_probe_blending.rs (line 651)
649fn set_help_text(app_status: &AppStatus, help_text_query: &mut Query<&mut Text, With<HelpText>>) {
650    for mut ui_text in help_text_query {
651        let mut help_text = String::new();
652        match app_status.camera_mode {
653            CameraMode::Orbit => {
654                help_text.push_str(
655                    "Click and drag to orbit the camera\nUse the mouse wheel to zoom the camera\n",
656                );
657            }
658            CameraMode::Free => {
659                help_text.push_str(
660                    "Click and drag to rotate the camera\nUse WASDEQ to move the camera\n",
661                );
662            }
663        }
664
665        help_text.push('\n');
666
667        if matches!(app_status.gizmos_enabled, GizmosEnabled::On) {
668            help_text.push_str(
669                "\
670Gizmos:
671Tan: Light probe bounds
672Red: Light probe falloff bounds
673Blue: Parallax correction bounds",
674            );
675        }
676
677        *ui_text = Text::new(help_text);
678    }
679}
examples/ecs/relationships.rs (line 83)
78    fn debug_relationships(
79        // Not all of our entities are targeted by something, so we use `Option` in our query to handle this case.
80        relations_query: Query<(&Name, &Targeting, Option<&TargetedBy>)>,
81        name_query: Query<&Name>,
82    ) {
83        let mut relationships = String::new();
84
85        for (name, targeting, maybe_targeted_by) in relations_query.iter() {
86            let targeting_name = name_query.get(targeting.0).unwrap();
87            let targeted_by_string = if let Some(targeted_by) = maybe_targeted_by {
88                let mut vec_of_names = Vec::<&Name>::new();
89
90                for entity in targeted_by.iter() {
91                    let name = name_query.get(entity).unwrap();
92                    vec_of_names.push(name);
93                }
94
95                // Convert this to a nice string for printing.
96                let vec_of_str: Vec<&str> = vec_of_names.iter().map(|name| name.as_str()).collect();
97                vec_of_str.join(", ")
98            } else {
99                "nobody".to_string()
100            };
101
102            relationships.push_str(&format!(
103                "{name} is targeting {targeting_name}, and is targeted by {targeted_by_string}\n",
104            ));
105        }
106
107        println!("{relationships}");
108    }
examples/3d/occlusion_culling.rs (line 525)
488fn update_status_text(
489    saved_indirect_parameters: Res<SavedIndirectParameters>,
490    mut texts: Query<&mut Text>,
491    meshes: Query<Entity, With<Mesh3d>>,
492    app_status: Res<AppStatus>,
493) {
494    // How many meshes are in the scene?
495    let total_mesh_count = meshes.iter().count();
496
497    // Sample the rendered object count. Note that we don't synchronize beyond
498    // locking the data and therefore this will value will generally at least
499    // one frame behind. This is fine; this app is just a demonstration after
500    // all.
501    let (
502        rendered_object_count,
503        occlusion_culling_supported,
504        occlusion_culling_introspection_supported,
505    ): (u32, bool, bool) = {
506        let saved_indirect_parameters = saved_indirect_parameters.lock().unwrap();
507        let Some(saved_indirect_parameters) = saved_indirect_parameters.as_ref() else {
508            // Bail out early if the resource isn't initialized yet.
509            return;
510        };
511        (
512            saved_indirect_parameters
513                .data
514                .iter()
515                .take(saved_indirect_parameters.count as usize)
516                .map(|indirect_parameters| indirect_parameters.instance_count)
517                .sum(),
518            saved_indirect_parameters.occlusion_culling_supported,
519            saved_indirect_parameters.occlusion_culling_introspection_supported,
520        )
521    };
522
523    // Change the text.
524    for mut text in &mut texts {
525        text.0 = String::new();
526        if !occlusion_culling_supported {
527            text.0
528                .push_str("Occlusion culling not supported on this platform");
529            continue;
530        }
531
532        let _ = writeln!(
533            &mut text.0,
534            "Occlusion culling {} (Press Space to toggle)",
535            if app_status.occlusion_culling {
536                "ON"
537            } else {
538                "OFF"
539            },
540        );
541
542        if !occlusion_culling_introspection_supported {
543            continue;
544        }
545
546        let _ = write!(
547            &mut text.0,
548            "{rendered_object_count}/{total_mesh_count} meshes rendered"
549        );
550    }
551}
examples/ui/text/multiline_text_input.rs (line 98)
28fn setup(mut commands: Commands, asset_server: Res<AssetServer>) {
29    commands.spawn(Camera2d);
30
31    commands
32        .spawn(Node {
33            width: percent(100.),
34            height: percent(100.),
35            justify_content: JustifyContent::Center,
36            align_items: AlignItems::Center,
37            ..default()
38        })
39        .with_children(|parent| {
40            parent
41                .spawn((
42                    Node {
43                        flex_direction: FlexDirection::Column,
44                        align_items: AlignItems::End,
45                        row_gap: px(10.),
46                        ..default()
47                    },
48                    TabGroup::default(),
49                ))
50                .with_children(|parent| {
51                    parent
52                        .spawn((
53                            Node {
54                                width: px(450.),
55                                border: px(2.).all(),
56                                padding: px(8.).all(),
57                                ..default()
58                            },
59                            EditableText {
60                                visible_lines: Some(8.),
61                                allow_newlines: true,
62                                ..default()
63                            },
64                            TextLayout {
65                                linebreak: LineBreak::WordOrCharacter,
66                                ..default()
67                            },
68                            TextCursorStyle {
69                                color: Color::WHITE,
70                                selected_text_color: Some(Color::BLACK),
71                                ..default()
72                            },
73                            TextFont {
74                                font: asset_server.load("fonts/FiraMono-Medium.ttf").into(),
75                                font_size: FontSize::Px(30.),
76                                ..default()
77                            },
78                            BackgroundColor(DARK_SLATE_GRAY.into()),
79                            BorderColor::all(SLATE_300),
80                            MultilineInput,
81                            TabIndex(0),
82                            AutoFocus,
83                        ))
84                        .observe(
85                            |on: On<FocusedInput<KeyboardInput>>,
86                             keys: Res<ButtonInput<Key>>,
87                             input_query: Query<&EditableText, With<MultilineInput>>| {
88                                if !(on.input.state.is_pressed()
89                                    && on.input.logical_key == Key::Enter
90                                    && keys.pressed(Key::Control))
91                                {
92                                    return;
93                                }
94                                let Ok(input) = input_query.get(on.focused_entity) else {
95                                    return;
96                                };
97
98                                let mut output = String::new();
99                                output.reserve(input.value().into_iter().map(str::len).sum());
100                                for sub_str in input.value() {
101                                    output.push_str(sub_str);
102                                }
103
104                                info!("{output}"                                    );
105                            },
106                        );
107
108                    parent
109                        .spawn((
110                            Node {
111                                flex_direction: FlexDirection::Row,
112                                column_gap: px(10.),
113                                ..default()
114                            },
115                            children![
116                                (
117                                    Text::new("visible lines:"),
118                                    TextFont {
119                                        font: asset_server.load("fonts/FiraMono-Medium.ttf").into(),
120                                        font_size: FontSize::Px(30.),
121                                        ..default()
122                                    },
123                                ),
124                                (
125                                    Node {
126                                        width: px(100.),
127                                        border: px(2.).all(),
128                                        ..default()
129                                    },
130                                    TextFont {
131                                        font: asset_server.load("fonts/FiraMono-Medium.ttf").into(),
132                                        font_size: FontSize::Px(30.),
133                                        ..default()
134                                    },
135                                    TextLayout {
136                                        justify: Justify::End,
137                                        ..default()
138                                    },
139                                    BackgroundColor(DARK_SLATE_GRAY.into()),
140                                    BorderColor::all(SLATE_300),
141                                    EditableText::new("8"),
142                                    EditableTextFilter::new(|c| c.is_ascii_digit() || c == '.'),
143                                    TextCursorStyle {
144                                        color: Color::WHITE,
145                                        selected_text_color: Some(Color::BLACK),
146                                        unfocused_selection_color: Color::NONE,
147                                        ..default()
148                                    },
149                                    SelectAllOnFocus,
150                                    VisibleLinesInput,
151                                    TabIndex(1),
152                                )
153                            ],
154                        ))
155                        .observe(
156                            |on: On<FocusedInput<KeyboardInput>>,
157                             mut query_set: ParamSet<(
158                                Query<&EditableText, With<VisibleLinesInput>>,
159                                Query<&mut EditableText, With<MultilineInput>>,
160                            )>| {
161                                if !(on.input.state.is_pressed()
162                                    && on.input.logical_key == Key::Enter)
163                                {
164                                    return;
165                                }
166
167                                let visible_lines_query = query_set.p0();
168                                let Ok(input) = visible_lines_query.get(on.original_event_target())
169                                else {
170                                    return;
171                                };
172
173                                let mut output = String::new();
174                                output.reserve(input.value().into_iter().map(str::len).sum());
175                                for sub_str in input.value() {
176                                    output.push_str(sub_str);
177                                }
178
179                                let Ok(lines) = output.parse::<f32>() else {
180                                    return;
181                                };
182
183                                let mut multiline_query = query_set.p1();
184                                let Ok(mut multiline_input) = multiline_query.single_mut() else {
185                                    return;
186                                };
187
188                                multiline_input.visible_lines = Some(lines.clamp(1., 10.));
189                            },
190                        );
191
192                    parent
193                        .spawn((
194                            Node {
195                                flex_direction: FlexDirection::Row,
196                                column_gap: px(10.),
197                                ..default()
198                            },
199                            children![
200                                (
201                                    Text::new("font size:"),
202                                    TextFont {
203                                        font: asset_server.load("fonts/FiraMono-Medium.ttf").into(),
204                                        font_size: FontSize::Px(30.),
205                                        ..default()
206                                    },
207                                ),
208                                (
209                                    Node {
210                                        width: px(100.),
211                                        border: px(2.).all(),
212                                        ..default()
213                                    },
214                                    TextFont {
215                                        font: asset_server.load("fonts/FiraMono-Medium.ttf").into(),
216                                        font_size: FontSize::Px(30.),
217                                        ..default()
218                                    },
219                                    TextLayout {
220                                        justify: Justify::End,
221                                        ..default()
222                                    },
223                                    BackgroundColor(DARK_SLATE_GRAY.into()),
224                                    BorderColor::all(SLATE_300),
225                                    EditableText::new("30"),
226                                    EditableTextFilter::new(|c| c.is_ascii_digit()),
227                                    TextCursorStyle {
228                                        color: Color::WHITE,
229                                        selected_text_color: Some(Color::BLACK),
230                                        unfocused_selection_color: Color::NONE,
231                                        ..default()
232                                    },
233                                    SelectAllOnFocus,
234                                    FontSizeInput,
235                                    TabIndex(2),
236                                )
237                            ],
238                        ))
239                        .observe(
240                            |on: On<FocusedInput<KeyboardInput>>,
241                             font_size_input_query: Query<&EditableText, With<FontSizeInput>>,
242                             mut multiline_input_font: Single<
243                                &mut TextFont,
244                                With<MultilineInput>,
245                            >| {
246                                if !(on.input.state.is_pressed()
247                                    && on.input.logical_key == Key::Enter)
248                                {
249                                    return;
250                                }
251
252                                let Ok(input) =
253                                    font_size_input_query.get(on.original_event_target())
254                                else {
255                                    return;
256                                };
257
258                                let mut output = String::new();
259                                output.reserve(input.value().into_iter().map(str::len).sum());
260                                for sub_str in input.value() {
261                                    output.push_str(sub_str);
262                                }
263
264                                let Ok(font_size) = output.parse::<f32>() else {
265                                    return;
266                                };
267
268                                multiline_input_font.font_size =
269                                    FontSize::Px(font_size.clamp(5., 50.));
270                            },
271                        );
272                });
273        });
274}
1.0.0 · Source

pub fn with_capacity(capacity: usize) -> String

Available on non-no_global_oom_handling only.

Creates a new empty String with at least the specified capacity.

Strings have an internal buffer to hold their data. The capacity is the length of that buffer, and can be queried with the capacity method. This method creates an empty String, but one with an initial buffer that can hold at least capacity bytes. This is useful when you may be appending a bunch of data to the String, reducing the number of reallocations it needs to do.

If the given capacity is 0, no allocation will occur, and this method is identical to the new method.

§Panics

Panics if the capacity exceeds isize::MAX bytes.

§Examples
let mut s = String::with_capacity(10);

// The String contains no chars, even though it has capacity for more
assert_eq!(s.len(), 0);

// These are all done without reallocating...
let cap = s.capacity();
for _ in 0..10 {
    s.push('a');
}

assert_eq!(s.capacity(), cap);

// ...but this may make the string reallocate
s.push('a');
Examples found in repository?
examples/3d/tonemapping.rs (line 419)
395fn update_ui(
396    mut text_query: Single<&mut Text, Without<SceneNumber>>,
397    settings: Single<(&Tonemapping, &ColorGrading)>,
398    current_scene: Res<CurrentScene>,
399    selected_parameter: Res<SelectedParameter>,
400    mut hide_ui: Local<bool>,
401    keys: Res<ButtonInput<KeyCode>>,
402) {
403    if keys.just_pressed(KeyCode::KeyH) {
404        *hide_ui = !*hide_ui;
405    }
406
407    if *hide_ui {
408        if !text_query.is_empty() {
409            // single_mut() always triggers change detection,
410            // so only access if text actually needs changing
411            text_query.clear();
412        }
413        return;
414    }
415
416    let (tonemapping, color_grading) = *settings;
417    let tonemapping = *tonemapping;
418
419    let mut text = String::with_capacity(text_query.len());
420
421    let scn = current_scene.0;
422    text.push_str("(H) Hide UI\n\n");
423    text.push_str("Test Scene: \n");
424    text.push_str(&format!(
425        "(Q) {} Basic Scene\n",
426        if scn == 1 { ">" } else { "" }
427    ));
428    text.push_str(&format!(
429        "(W) {} Color Sweep\n",
430        if scn == 2 { ">" } else { "" }
431    ));
432    text.push_str(&format!(
433        "(E) {} Image Viewer\n",
434        if scn == 3 { ">" } else { "" }
435    ));
436
437    text.push_str("\n\nTonemapping Method:\n");
438    text.push_str(&format!(
439        "(1) {} Disabled\n",
440        if tonemapping == Tonemapping::None {
441            ">"
442        } else {
443            ""
444        }
445    ));
446    text.push_str(&format!(
447        "(2) {} Reinhard\n",
448        if tonemapping == Tonemapping::Reinhard {
449            "> "
450        } else {
451            ""
452        }
453    ));
454    text.push_str(&format!(
455        "(3) {} Reinhard Luminance\n",
456        if tonemapping == Tonemapping::ReinhardLuminance {
457            ">"
458        } else {
459            ""
460        }
461    ));
462    text.push_str(&format!(
463        "(4) {} ACES Fitted\n",
464        if tonemapping == Tonemapping::AcesFitted {
465            ">"
466        } else {
467            ""
468        }
469    ));
470    text.push_str(&format!(
471        "(5) {} AgX\n",
472        if tonemapping == Tonemapping::AgX {
473            ">"
474        } else {
475            ""
476        }
477    ));
478    text.push_str(&format!(
479        "(6) {} SomewhatBoringDisplayTransform\n",
480        if tonemapping == Tonemapping::SomewhatBoringDisplayTransform {
481            ">"
482        } else {
483            ""
484        }
485    ));
486    text.push_str(&format!(
487        "(7) {} TonyMcMapface\n",
488        if tonemapping == Tonemapping::TonyMcMapface {
489            ">"
490        } else {
491            ""
492        }
493    ));
494    text.push_str(&format!(
495        "(8) {} Blender Filmic\n",
496        if tonemapping == Tonemapping::BlenderFilmic {
497            ">"
498        } else {
499            ""
500        }
501    ));
502    text.push_str(&format!(
503        "(9) {} Khronos PBR Neutral\n",
504        if tonemapping == Tonemapping::KhronosPbrNeutral {
505            ">"
506        } else {
507            ""
508        }
509    ));
510
511    text.push_str("\n\nColor Grading:\n");
512    text.push_str("(arrow keys)\n");
513    if selected_parameter.value == 0 {
514        text.push_str("> ");
515    }
516    text.push_str(&format!("Exposure: {:.2}\n", color_grading.global.exposure));
517    if selected_parameter.value == 1 {
518        text.push_str("> ");
519    }
520    text.push_str(&format!("Gamma: {:.2}\n", color_grading.shadows.gamma));
521    if selected_parameter.value == 2 {
522        text.push_str("> ");
523    }
524    text.push_str(&format!(
525        "PreSaturation: {:.2}\n",
526        color_grading.shadows.saturation
527    ));
528    if selected_parameter.value == 3 {
529        text.push_str("> ");
530    }
531    text.push_str(&format!(
532        "PostSaturation: {:.2}\n",
533        color_grading.global.post_saturation
534    ));
535    text.push_str("(Space) Reset all to default\n");
536
537    if current_scene.0 == 1 {
538        text.push_str("(Enter) Reset all to scene recommendation\n");
539    }
540
541    if text != text_query.as_str() {
542        // single_mut() always triggers change detection,
543        // so only access if text actually changed
544        text_query.0 = text;
545    }
546}
Source

pub fn try_with_capacity(capacity: usize) -> Result<String, TryReserveError>

🔬This is a nightly-only experimental API. (try_with_capacity)

Creates a new empty String with at least the specified capacity.

§Errors

Returns Err if the capacity exceeds isize::MAX bytes, or if the memory allocator reports failure.

1.0.0 · Source

pub fn from_utf8(vec: Vec<u8>) -> Result<String, FromUtf8Error>

Converts a vector of bytes to a String.

A string (String) is made of bytes (u8), and a vector of bytes (Vec<u8>) is made of bytes, so this function converts between the two. Not all byte slices are valid Strings, however: String requires that it is valid UTF-8. from_utf8() checks to ensure that the bytes are valid UTF-8, and then does the conversion.

If you are sure that the byte slice is valid UTF-8, and you don’t want to incur the overhead of the validity check, there is an unsafe version of this function, from_utf8_unchecked, which has the same behavior but skips the check.

This method will take care to not copy the vector, for efficiency’s sake.

If you need a &str instead of a String, consider str::from_utf8.

The inverse of this method is into_bytes.

§Errors

Returns Err if the slice is not UTF-8 with a description as to why the provided bytes are not UTF-8. The vector you moved in is also included.

§Examples

Basic usage:

// some bytes, in a vector
let sparkle_heart = vec![240, 159, 146, 150];

// We know these bytes are valid, so we'll use `unwrap()`.
let sparkle_heart = String::from_utf8(sparkle_heart).unwrap();

assert_eq!("💖", sparkle_heart);

Incorrect bytes:

// some invalid bytes, in a vector
let sparkle_heart = vec![0, 159, 146, 150];

assert!(String::from_utf8(sparkle_heart).is_err());

See the docs for FromUtf8Error for more details on what you can do with this error.

Examples found in repository?
examples/asset/processing/asset_processing.rs (line 95)
84    async fn load(
85        &self,
86        reader: &mut dyn Reader,
87        settings: &TextSettings,
88        _load_context: &mut LoadContext<'_>,
89    ) -> Result<Text, Self::Error> {
90        let mut bytes = Vec::new();
91        reader.read_to_end(&mut bytes).await?;
92        let value = if let Some(ref text) = settings.text_override {
93            text.clone()
94        } else {
95            String::from_utf8(bytes).unwrap()
96        };
97        Ok(Text(value))
98    }
1.0.0 · Source

pub fn from_utf8_lossy(v: &[u8]) -> Cow<'_, str>

Available on non-no_global_oom_handling only.

Converts a slice of bytes to a string, including invalid characters.

Strings are made of bytes (u8), and a slice of bytes (&[u8]) is made of bytes, so this function converts between the two. Not all byte slices are valid strings, however: strings are required to be valid UTF-8. During this conversion, from_utf8_lossy() will replace any invalid UTF-8 sequences with U+FFFD REPLACEMENT CHARACTER, which looks like this: �

If you are sure that the byte slice is valid UTF-8, and you don’t want to incur the overhead of the conversion, there is an unsafe version of this function, from_utf8_unchecked, which has the same behavior but skips the checks.

This function returns a Cow<'a, str>. If our byte slice is invalid UTF-8, then we need to insert the replacement characters, which will change the size of the string, and hence, require a String. But if it’s already valid UTF-8, we don’t need a new allocation. This return type allows us to handle both cases.

§Examples

Basic usage:

// some bytes, in a vector
let sparkle_heart = vec![240, 159, 146, 150];

let sparkle_heart = String::from_utf8_lossy(&sparkle_heart);

assert_eq!("💖", sparkle_heart);

Incorrect bytes:

// some invalid bytes
let input = b"Hello \xF0\x90\x80World";
let output = String::from_utf8_lossy(input);

assert_eq!("Hello �World", output);
1.99.0 · Source

pub fn from_utf8_lossy_owned(v: Vec<u8>) -> String

Available on non-no_global_oom_handling only.

Converts a Vec<u8> to a String, substituting invalid UTF-8 sequences with replacement characters.

See from_utf8_lossy for more details.

Note that this function does not guarantee reuse of the original Vec allocation.

§Examples

Basic usage:

// some bytes, in a vector
let sparkle_heart = vec![240, 159, 146, 150];

let sparkle_heart = String::from_utf8_lossy_owned(sparkle_heart);

assert_eq!(String::from("💖"), sparkle_heart);

Incorrect bytes:

// some invalid bytes
let input: Vec<u8> = b"Hello \xF0\x90\x80World".into();
let output = String::from_utf8_lossy_owned(input);

assert_eq!(String::from("Hello �World"), output);
1.0.0 · Source

pub fn from_utf16(v: &[u16]) -> Result<String, FromUtf16Error>

Available on non-no_global_oom_handling only.

Decode a native endian UTF-16–encoded vector v into a String, returning Err if v contains any invalid data.

§Examples
// 𝄞music
let v = &[0xD834, 0xDD1E, 0x006d, 0x0075,
          0x0073, 0x0069, 0x0063];
assert_eq!(String::from("𝄞music"),
           String::from_utf16(v).unwrap());

// 𝄞mu<invalid>ic
let v = &[0xD834, 0xDD1E, 0x006d, 0x0075,
          0xD800, 0x0069, 0x0063];
assert!(String::from_utf16(v).is_err());
1.0.0 · Source

pub fn from_utf16_lossy(v: &[u16]) -> String

Available on non-no_global_oom_handling only.

Decode a native endian UTF-16–encoded slice v into a String, replacing invalid data with the replacement character (U+FFFD).

Unlike from_utf8_lossy which returns a Cow<'a, str>, from_utf16_lossy returns a String since the UTF-16 to UTF-8 conversion requires a memory allocation.

§Examples
// 𝄞mus<invalid>ic<invalid>
let v = &[0xD834, 0xDD1E, 0x006d, 0x0075,
          0x0073, 0xDD1E, 0x0069, 0x0063,
          0xD834];

assert_eq!(String::from("𝄞mus\u{FFFD}ic\u{FFFD}"),
           String::from_utf16_lossy(v));
1.98.0 · Source

pub fn from_utf16le(v: &[u8]) -> Result<String, FromUtf16Error>

Available on non-no_global_oom_handling only.

Decode a UTF-16LE–encoded vector v into a String, returning Err if v contains any invalid data.

§Examples

Basic usage:

// 𝄞music
let v = &[0x34, 0xD8, 0x1E, 0xDD, 0x6d, 0x00, 0x75, 0x00,
          0x73, 0x00, 0x69, 0x00, 0x63, 0x00];
assert_eq!(String::from("𝄞music"),
           String::from_utf16le(v).unwrap());

// 𝄞mu<invalid>ic
let v = &[0x34, 0xD8, 0x1E, 0xDD, 0x6d, 0x00, 0x75, 0x00,
          0x00, 0xD8, 0x69, 0x00, 0x63, 0x00];
assert!(String::from_utf16le(v).is_err());
1.98.0 · Source

pub fn from_utf16le_lossy(v: &[u8]) -> String

Available on non-no_global_oom_handling only.

Decode a UTF-16LE–encoded slice v into a String, replacing invalid data with the replacement character (U+FFFD).

Unlike from_utf8_lossy which returns a Cow<'a, str>, from_utf16le_lossy returns a String since the UTF-16 to UTF-8 conversion requires a memory allocation.

§Examples

Basic usage:

// 𝄞mus<invalid>ic<invalid>
let v = &[0x34, 0xD8, 0x1E, 0xDD, 0x6d, 0x00, 0x75, 0x00,
          0x73, 0x00, 0x1E, 0xDD, 0x69, 0x00, 0x63, 0x00,
          0x34, 0xD8];

assert_eq!(String::from("𝄞mus\u{FFFD}ic\u{FFFD}"),
           String::from_utf16le_lossy(v));
1.98.0 · Source

pub fn from_utf16be(v: &[u8]) -> Result<String, FromUtf16Error>

Available on non-no_global_oom_handling only.

Decode a UTF-16BE–encoded vector v into a String, returning Err if v contains any invalid data.

§Examples

Basic usage:

// 𝄞music
let v = &[0xD8, 0x34, 0xDD, 0x1E, 0x00, 0x6d, 0x00, 0x75,
          0x00, 0x73, 0x00, 0x69, 0x00, 0x63];
assert_eq!(String::from("𝄞music"),
           String::from_utf16be(v).unwrap());

// 𝄞mu<invalid>ic
let v = &[0xD8, 0x34, 0xDD, 0x1E, 0x00, 0x6d, 0x00, 0x75,
          0xD8, 0x00, 0x00, 0x69, 0x00, 0x63];
assert!(String::from_utf16be(v).is_err());
1.98.0 · Source

pub fn from_utf16be_lossy(v: &[u8]) -> String

Available on non-no_global_oom_handling only.

Decode a UTF-16BE–encoded slice v into a String, replacing invalid data with the replacement character (U+FFFD).

Unlike from_utf8_lossy which returns a Cow<'a, str>, from_utf16le_lossy returns a String since the UTF-16 to UTF-8 conversion requires a memory allocation.

§Examples

Basic usage:

// 𝄞mus<invalid>ic<invalid>
let v = &[0xD8, 0x34, 0xDD, 0x1E, 0x00, 0x6d, 0x00, 0x75,
          0x00, 0x73, 0xDD, 0x1E, 0x00, 0x69, 0x00, 0x63,
          0xD8, 0x34];

assert_eq!(String::from("𝄞mus\u{FFFD}ic\u{FFFD}"),
           String::from_utf16be_lossy(v));
1.93.0 · Source

pub fn into_raw_parts(self) -> (*mut u8, usize, usize)

Decomposes a String into its raw components: (pointer, length, capacity).

Returns the raw pointer to the underlying data, the length of the string (in bytes), and the allocated capacity of the data (in bytes). These are the same arguments in the same order as the arguments to from_raw_parts.

After calling this function, the caller is responsible for the memory previously managed by the String. The only way to do this is to convert the raw pointer, length, and capacity back into a String with the from_raw_parts function, allowing the destructor to perform the cleanup.

§Examples
let s = String::from("hello");

let (ptr, len, cap) = s.into_raw_parts();

let rebuilt = unsafe { String::from_raw_parts(ptr, len, cap) };
assert_eq!(rebuilt, "hello");
1.0.0 · Source

pub unsafe fn from_raw_parts( buf: *mut u8, length: usize, capacity: usize, ) -> String

Creates a new String from a pointer, a length and a capacity.

§Safety

This is highly unsafe, due to the number of invariants that aren’t checked:

Violating these may cause problems like corrupting the allocator’s internal data structures. For example, it is normally not safe to build a String from a pointer to a C char array containing UTF-8 unless you are certain that array was originally allocated by the Rust standard library’s allocator.

The ownership of buf is effectively transferred to the String which may then deallocate, reallocate or change the contents of memory pointed to by the pointer at will. Ensure that nothing else uses the pointer after calling this function.

§Examples
unsafe {
    let s = String::from("hello");

    // Deconstruct the String into parts.
    let (ptr, len, capacity) = s.into_raw_parts();

    let s = String::from_raw_parts(ptr, len, capacity);

    assert_eq!(String::from("hello"), s);
}
1.0.0 · Source

pub unsafe fn from_utf8_unchecked(bytes: Vec<u8>) -> String

Converts a vector of bytes to a String without checking that the string contains valid UTF-8.

See the safe version, from_utf8, for more details.

§Safety

This function is unsafe because it does not check that the bytes passed to it are valid UTF-8. If this constraint is violated, it may cause memory unsafety issues with future users of the String, as the rest of the standard library assumes that Strings are valid UTF-8.

§Examples
// some bytes, in a vector
let sparkle_heart = vec![240, 159, 146, 150];

let sparkle_heart = unsafe {
    String::from_utf8_unchecked(sparkle_heart)
};

assert_eq!("💖", sparkle_heart);
1.0.0 (const: 1.87.0) · Source

pub const fn into_bytes(self) -> Vec<u8>

Converts a String into a byte vector.

This consumes the String, so we do not need to copy its contents.

§Examples
let s = String::from("hello");
let bytes = s.into_bytes();

assert_eq!(&[104, 101, 108, 108, 111][..], &bytes[..]);
1.7.0 (const: 1.87.0) · Source

pub const fn as_str(&self) -> &str

Extracts a string slice containing the entire String.

§Examples
let s = String::from("foo");

assert_eq!("foo", s.as_str());
Examples found in repository?
examples/time/time.rs (line 44)
35fn runner(mut app: App) -> AppExit {
36    banner();
37    help();
38    let stdin = io::stdin();
39    for line in stdin.lock().lines() {
40        if let Err(err) = line {
41            println!("read err: {err:#}");
42            break;
43        }
44        match line.unwrap().as_str() {
45            "" => {
46                app.update();
47            }
48            "f" => {
49                println!("FAST: setting relative speed to 2x");
50                app.world_mut()
51                    .resource_mut::<Time<Virtual>>()
52                    .set_relative_speed(2.0);
53            }
54            "n" => {
55                println!("NORMAL: setting relative speed to 1x");
56                app.world_mut()
57                    .resource_mut::<Time<Virtual>>()
58                    .set_relative_speed(1.0);
59            }
60            "s" => {
61                println!("SLOW: setting relative speed to 0.5x");
62                app.world_mut()
63                    .resource_mut::<Time<Virtual>>()
64                    .set_relative_speed(0.5);
65            }
66            "p" => {
67                println!("PAUSE: pausing virtual clock");
68                app.world_mut().resource_mut::<Time<Virtual>>().pause();
69            }
70            "u" => {
71                println!("UNPAUSE: resuming virtual clock");
72                app.world_mut().resource_mut::<Time<Virtual>>().unpause();
73            }
74            "q" => {
75                println!("QUITTING!");
76                break;
77            }
78            _ => {
79                help();
80            }
81        }
82    }
83
84    AppExit::Success
85}
More examples
Hide additional examples
examples/gltf/edit_material_on_gltf.rs (line 83)
55fn change_material(
56    scene_ready: On<WorldInstanceReady>,
57    mut commands: Commands,
58    children: Query<&Children>,
59    color_override: Query<&ColorOverride>,
60    mesh_materials: Query<(&MeshMaterial3d<StandardMaterial>, &GltfMaterialName)>,
61    mut asset_materials: ResMut<Assets<StandardMaterial>>,
62) {
63    info!("processing Scene Entity: {}", scene_ready.entity);
64
65    // Get the `ColorOverride` of the entity, if it does not have a color override, return
66    let Ok(color_override) = color_override.get(scene_ready.entity) else {
67        info!("{} does not have a color override", scene_ready.entity);
68        return;
69    };
70
71    // Iterate over all children recursively
72    for descendant in children.iter_descendants(scene_ready.entity) {
73        // Get the material id and name which were created from the glTF file information
74        let Ok((id, material_name)) = mesh_materials.get(descendant) else {
75            continue;
76        };
77        // Get the material of the descendant
78        let Some(material) = asset_materials.get(id.id()) else {
79            continue;
80        };
81
82        // match on the material name, modifying the materials as necessary
83        match material_name.0.as_str() {
84            "LeatherPartsMat" => {
85                info!("editing LeatherPartsMat to use ColorOverride tint");
86                // Create a copy of the material and override base color
87                // If you intend on creating multiple models with the same tint, it
88                // is best to cache the handle somewhere, as having multiple materials
89                // that are identical is expensive
90                let mut new_material = material.clone();
91                new_material.base_color = color_override.0;
92
93                // Override `MeshMaterial3d` with new material
94                commands
95                    .entity(descendant)
96                    .insert(MeshMaterial3d(asset_materials.add(new_material)));
97            }
98            name => {
99                info!("not replacing: {name}");
100            }
101        }
102    }
103}
examples/3d/solari.rs (line 424)
374fn add_raytracing_meshes_on_scene_load(
375    scene_ready: On<WorldInstanceReady>,
376    children: Query<&Children>,
377    mesh_query: Query<(
378        &Mesh3d,
379        &MeshMaterial3d<StandardMaterial>,
380        Option<&GltfMaterialName>,
381    )>,
382    mut meshes: ResMut<Assets<Mesh>>,
383    mut materials: ResMut<Assets<StandardMaterial>>,
384    mut commands: Commands,
385    args: Res<Args>,
386) {
387    for descendant in children.iter_descendants(scene_ready.entity) {
388        if let Ok((Mesh3d(mesh_handle), MeshMaterial3d(material_handle), material_name)) =
389            mesh_query.get(descendant)
390        {
391            // Add raytracing mesh component
392            commands
393                .entity(descendant)
394                .insert(RaytracingMesh3d(mesh_handle.clone()));
395
396            // Ensure meshes are Solari compatible
397            let mut mesh = meshes.get_mut(mesh_handle).unwrap();
398            if !mesh.contains_attribute(Mesh::ATTRIBUTE_UV_0) {
399                let vertex_count = mesh.count_vertices();
400                mesh.insert_attribute(Mesh::ATTRIBUTE_UV_0, vec![[0.0, 0.0]; vertex_count]);
401                mesh.insert_attribute(
402                    Mesh::ATTRIBUTE_TANGENT,
403                    vec![[0.0, 0.0, 0.0, 0.0]; vertex_count],
404                );
405            }
406            if !mesh.contains_attribute(Mesh::ATTRIBUTE_TANGENT) {
407                mesh.generate_tangents().unwrap();
408            }
409            if mesh.contains_attribute(Mesh::ATTRIBUTE_UV_1) {
410                mesh.remove_attribute(Mesh::ATTRIBUTE_UV_1);
411            }
412            if let Some(indices) = mesh.indices_mut()
413                && let Indices::U16(_) = indices
414            {
415                *indices = Indices::U32(indices.iter().map(|i| i as u32).collect());
416            }
417
418            // Prevent rasterization if using pathtracer
419            if args.pathtracer == Some(true) {
420                commands.entity(descendant).remove::<Mesh3d>();
421            }
422
423            // Adjust scene materials to better demo Solari features
424            if material_name.map(|s| s.0.as_str()) == Some("material") {
425                let mut material = materials.get_mut(material_handle).unwrap();
426                material.emissive = LinearRgba::BLACK;
427            }
428            if material_name.map(|s| s.0.as_str()) == Some("Lights") {
429                let mut material = materials.get_mut(material_handle).unwrap();
430                material.emissive =
431                    LinearRgba::from(Color::srgb(0.941, 0.714, 0.043)) * 1_000_000.0;
432                material.alpha_mode = AlphaMode::Opaque;
433                material.specular_transmission = 0.0;
434
435                commands.insert_resource(RobotLightMaterial(material_handle.clone()));
436            }
437            if material_name.map(|s| s.0.as_str()) == Some("Glass_Dark_01") {
438                let mut material = materials.get_mut(material_handle).unwrap();
439                material.alpha_mode = AlphaMode::Opaque;
440                material.specular_transmission = 0.0;
441            }
442        }
443    }
444}
examples/3d/tonemapping.rs (line 541)
395fn update_ui(
396    mut text_query: Single<&mut Text, Without<SceneNumber>>,
397    settings: Single<(&Tonemapping, &ColorGrading)>,
398    current_scene: Res<CurrentScene>,
399    selected_parameter: Res<SelectedParameter>,
400    mut hide_ui: Local<bool>,
401    keys: Res<ButtonInput<KeyCode>>,
402) {
403    if keys.just_pressed(KeyCode::KeyH) {
404        *hide_ui = !*hide_ui;
405    }
406
407    if *hide_ui {
408        if !text_query.is_empty() {
409            // single_mut() always triggers change detection,
410            // so only access if text actually needs changing
411            text_query.clear();
412        }
413        return;
414    }
415
416    let (tonemapping, color_grading) = *settings;
417    let tonemapping = *tonemapping;
418
419    let mut text = String::with_capacity(text_query.len());
420
421    let scn = current_scene.0;
422    text.push_str("(H) Hide UI\n\n");
423    text.push_str("Test Scene: \n");
424    text.push_str(&format!(
425        "(Q) {} Basic Scene\n",
426        if scn == 1 { ">" } else { "" }
427    ));
428    text.push_str(&format!(
429        "(W) {} Color Sweep\n",
430        if scn == 2 { ">" } else { "" }
431    ));
432    text.push_str(&format!(
433        "(E) {} Image Viewer\n",
434        if scn == 3 { ">" } else { "" }
435    ));
436
437    text.push_str("\n\nTonemapping Method:\n");
438    text.push_str(&format!(
439        "(1) {} Disabled\n",
440        if tonemapping == Tonemapping::None {
441            ">"
442        } else {
443            ""
444        }
445    ));
446    text.push_str(&format!(
447        "(2) {} Reinhard\n",
448        if tonemapping == Tonemapping::Reinhard {
449            "> "
450        } else {
451            ""
452        }
453    ));
454    text.push_str(&format!(
455        "(3) {} Reinhard Luminance\n",
456        if tonemapping == Tonemapping::ReinhardLuminance {
457            ">"
458        } else {
459            ""
460        }
461    ));
462    text.push_str(&format!(
463        "(4) {} ACES Fitted\n",
464        if tonemapping == Tonemapping::AcesFitted {
465            ">"
466        } else {
467            ""
468        }
469    ));
470    text.push_str(&format!(
471        "(5) {} AgX\n",
472        if tonemapping == Tonemapping::AgX {
473            ">"
474        } else {
475            ""
476        }
477    ));
478    text.push_str(&format!(
479        "(6) {} SomewhatBoringDisplayTransform\n",
480        if tonemapping == Tonemapping::SomewhatBoringDisplayTransform {
481            ">"
482        } else {
483            ""
484        }
485    ));
486    text.push_str(&format!(
487        "(7) {} TonyMcMapface\n",
488        if tonemapping == Tonemapping::TonyMcMapface {
489            ">"
490        } else {
491            ""
492        }
493    ));
494    text.push_str(&format!(
495        "(8) {} Blender Filmic\n",
496        if tonemapping == Tonemapping::BlenderFilmic {
497            ">"
498        } else {
499            ""
500        }
501    ));
502    text.push_str(&format!(
503        "(9) {} Khronos PBR Neutral\n",
504        if tonemapping == Tonemapping::KhronosPbrNeutral {
505            ">"
506        } else {
507            ""
508        }
509    ));
510
511    text.push_str("\n\nColor Grading:\n");
512    text.push_str("(arrow keys)\n");
513    if selected_parameter.value == 0 {
514        text.push_str("> ");
515    }
516    text.push_str(&format!("Exposure: {:.2}\n", color_grading.global.exposure));
517    if selected_parameter.value == 1 {
518        text.push_str("> ");
519    }
520    text.push_str(&format!("Gamma: {:.2}\n", color_grading.shadows.gamma));
521    if selected_parameter.value == 2 {
522        text.push_str("> ");
523    }
524    text.push_str(&format!(
525        "PreSaturation: {:.2}\n",
526        color_grading.shadows.saturation
527    ));
528    if selected_parameter.value == 3 {
529        text.push_str("> ");
530    }
531    text.push_str(&format!(
532        "PostSaturation: {:.2}\n",
533        color_grading.global.post_saturation
534    ));
535    text.push_str("(Space) Reset all to default\n");
536
537    if current_scene.0 == 1 {
538        text.push_str("(Enter) Reset all to scene recommendation\n");
539    }
540
541    if text != text_query.as_str() {
542        // single_mut() always triggers change detection,
543        // so only access if text actually changed
544        text_query.0 = text;
545    }
546}
1.7.0 (const: 1.87.0) · Source

pub const fn as_mut_str(&mut self) -> &mut str

Converts a String into a mutable string slice.

§Examples
let mut s = String::from("foobar");
let s_mut_str = s.as_mut_str();

s_mut_str.make_ascii_uppercase();

assert_eq!("FOOBAR", s_mut_str);
1.0.0 · Source

pub fn push_str(&mut self, string: &str)

Available on non-no_global_oom_handling only.

Appends a given string slice onto the end of this String.

§Panics

Panics if the new capacity exceeds isize::MAX bytes.

§Examples
let mut s = String::from("foo");

s.push_str("bar");

assert_eq!("foobar", s);
Examples found in repository?
examples/stress_tests/many_text.rs (line 213)
209fn update_lorem_text(mut lorem_text_query: Query<(&mut Text, &mut Lorem)>) {
210    for (mut text, mut lorem) in &mut lorem_text_query {
211        if lorem.0 {
212            text.0.clear();
213            text.0.push_str(LOREM_TEXT_1);
214        } else {
215            text.0.clear();
216            text.0.push_str(LOREM_TEXT_2);
217        }
218
219        lorem.0 = !lorem.0;
220    }
221}
More examples
Hide additional examples
examples/math/bounding_2d.rs (line 82)
75fn update_text(mut text: Single<&mut Text>, cur_state: Res<State<Test>>) {
76    if !cur_state.is_changed() {
77        return;
78    }
79
80    text.clear();
81
82    text.push_str("Intersection test:\n");
83    use Test::*;
84    for &test in &[AabbSweep, CircleSweep, RayCast, AabbCast, CircleCast] {
85        let s = if **cur_state == test { "*" } else { " " };
86        text.push_str(&format!(" {s} {test:?} {s}\n"));
87    }
88    text.push_str("\nPress space to cycle");
89}
examples/shader_advanced/fullscreen_material.rs (line 105)
93fn toggle_effect(
94    mut text: Single<&mut Text>,
95    keys: Res<ButtonInput<KeyCode>>,
96    camera: Single<(Entity, Option<&FullscreenEffect>), With<Camera3d>>,
97    mut commands: Commands,
98) {
99    if keys.just_pressed(KeyCode::KeyT) {
100        let (entity, effect) = *camera;
101
102        if effect.is_some() {
103            commands.entity(entity).remove::<FullscreenEffect>();
104            text.clear();
105            text.push_str("(T) FullscreenEffect: Off");
106        } else {
107            commands.entity(entity).insert(FullscreenEffect::new(0.0));
108            text.clear();
109            text.push_str("(T) FullscreenEffect: On");
110        }
111    }
112}
examples/ecs/entity_disabling.rs (line 68)
59fn list_all_named_entities(
60    query: Query<&Name>,
61    mut name_text_query: Query<&mut Text, With<EntityNameText>>,
62    mut commands: Commands,
63) {
64    let mut text_string = String::from("Named entities found:\n");
65    // Query iteration order is not guaranteed, so we sort the names
66    // to ensure the output is consistent.
67    for name in query.iter().sort::<&Name>() {
68        text_string.push_str(&format!("{name:?}\n"));
69    }
70
71    if let Ok(mut text) = name_text_query.single_mut() {
72        *text = Text::new(text_string);
73    } else {
74        commands.spawn((
75            EntityNameText,
76            Text::default(),
77            Node {
78                position_type: PositionType::Absolute,
79                top: px(12),
80                right: px(12),
81                ..default()
82            },
83        ));
84    }
85}
examples/ui/images/image_node_resizing.rs (lines 229-232)
219fn update_text(
220    event: On<TextUpdate>,
221    mut textmeta: Single<&mut TextData>,
222    mut text: Single<&mut Text>,
223) {
224    let mut new_text = Text::new(TEXT_PREFIX);
225    match event.direction {
226        Direction::Height => {
227            textmeta.height = (textmeta.height + event.change)
228                .clamp(IMAGE_GROUP_BOX_MIN_HEIGHT, IMAGE_GROUP_BOX_MAX_HEIGHT);
229            new_text.push_str(&format!(
230                "height : {}%, width : {}%",
231                textmeta.height, textmeta.width
232            ));
233        }
234        Direction::Width => {
235            textmeta.width = (textmeta.width + event.change)
236                .clamp(IMAGE_GROUP_BOX_MIN_WIDTH, IMAGE_GROUP_BOX_MAX_WIDTH);
237            new_text.push_str(&format!(
238                "height : {}%, width : {}%",
239                textmeta.height, textmeta.width
240            ));
241        }
242    }
243    text.0 = new_text.0;
244}
examples/3d/light_probe_blending.rs (lines 654-656)
649fn set_help_text(app_status: &AppStatus, help_text_query: &mut Query<&mut Text, With<HelpText>>) {
650    for mut ui_text in help_text_query {
651        let mut help_text = String::new();
652        match app_status.camera_mode {
653            CameraMode::Orbit => {
654                help_text.push_str(
655                    "Click and drag to orbit the camera\nUse the mouse wheel to zoom the camera\n",
656                );
657            }
658            CameraMode::Free => {
659                help_text.push_str(
660                    "Click and drag to rotate the camera\nUse WASDEQ to move the camera\n",
661                );
662            }
663        }
664
665        help_text.push('\n');
666
667        if matches!(app_status.gizmos_enabled, GizmosEnabled::On) {
668            help_text.push_str(
669                "\
670Gizmos:
671Tan: Light probe bounds
672Red: Light probe falloff bounds
673Blue: Parallax correction bounds",
674            );
675        }
676
677        *ui_text = Text::new(help_text);
678    }
679}
1.87.0 · Source

pub fn extend_from_within<R>(&mut self, src: R)
where R: RangeBounds<usize>,

Available on non-no_global_oom_handling only.

Copies elements from src range to the end of the string.

§Panics

Panics if the range has start_bound > end_bound, if the range is bounded on either end and does not lie on a char boundary, or if the new capacity exceeds isize::MAX bytes.

§Examples
let mut string = String::from("abcde");

string.extend_from_within(2..);
assert_eq!(string, "abcdecde");

string.extend_from_within(..2);
assert_eq!(string, "abcdecdeab");

string.extend_from_within(4..8);
assert_eq!(string, "abcdecdeabecde");
1.0.0 (const: 1.87.0) · Source

pub const fn capacity(&self) -> usize

Returns this String’s capacity, in bytes.

§Examples
let s = String::with_capacity(10);

assert!(s.capacity() >= 10);
1.0.0 · Source

pub fn reserve(&mut self, additional: usize)

Available on non-no_global_oom_handling only.

Reserves capacity for at least additional bytes more than the current length. The allocator may reserve more space to speculatively avoid frequent allocations. After calling reserve, capacity will be greater than or equal to self.len() + additional. Does nothing if capacity is already sufficient.

§Panics

Panics if the new capacity exceeds isize::MAX bytes.

§Examples

Basic usage:

let mut s = String::new();

s.reserve(10);

assert!(s.capacity() >= 10);

This might not actually increase the capacity:

let mut s = String::with_capacity(10);
s.push('a');
s.push('b');

// s now has a length of 2 and a capacity of at least 10
let capacity = s.capacity();
assert_eq!(2, s.len());
assert!(capacity >= 10);

// Since we already have at least an extra 8 capacity, calling this...
s.reserve(8);

// ... doesn't actually increase.
assert_eq!(capacity, s.capacity());
Examples found in repository?
examples/ui/text/multiple_text_inputs.rs (line 192)
177fn synchronize_output_text(
178    changed_inputs: Query<(&EditableText, &TextInputRow), Changed<EditableText>>,
179    mut outputs: Query<(&mut Text, &TextInputRow), With<TextOutput>>,
180) {
181    for (editable_text, input_row) in &changed_inputs {
182        for (mut text, output_row) in &mut outputs {
183            if output_row.0 == input_row.0 {
184                // `EditableText::value()` returns a `SplitString` because Parley may keep IME preedit text
185                // in a contiguous range of the editor’s internal `String` buffer during composition.
186                // The returned `SplitString` omits that preedit range, exposing only the text before and after it.
187                //
188                // To avoid allocating a new `String`, we reserve the total length of the `SplitString`'s slices,
189                // then append them to the output `Text`.
190                text.0.clear();
191                text.0
192                    .reserve(editable_text.value().into_iter().map(str::len).sum());
193                for sub_str in editable_text.value() {
194                    text.0.push_str(sub_str);
195                }
196            }
197        }
198    }
199}
200
201// Submit the focused input's text when Enter is pressed.
202fn submit_text(
203    mut input_focus: ResMut<InputFocus>,
204    keyboard_input: Res<ButtonInput<Key>>,
205    mut text_input: Query<(&mut EditableText, &TextInputRow)>,
206    mut text_output: Query<(&mut Text, &TextInputRow), With<SubmitOutput>>,
207    tab_navigation: TabNavigation,
208) {
209    if keyboard_input.just_pressed(Key::Enter)
210        && let Some(focused_entity) = input_focus.get()
211        && let Ok((mut editable_text, input_row)) = text_input.get_mut(focused_entity)
212    {
213        for (mut text, output_row) in &mut text_output {
214            if input_row.0 == output_row.0 {
215                text.0.clear();
216                text.0
217                    .reserve(editable_text.value().into_iter().map(str::len).sum());
218                for sub_str in editable_text.value() {
219                    text.0.push_str(sub_str);
220                }
221                break;
222            }
223        }
224        editable_text.clear();
225
226        if let Ok(next) = tab_navigation.navigate(&input_focus, NavAction::Next) {
227            input_focus.set(next, FocusCause::Navigated);
228        }
229    }
230}
More examples
Hide additional examples
examples/ui/text/multiline_text_input.rs (line 99)
28fn setup(mut commands: Commands, asset_server: Res<AssetServer>) {
29    commands.spawn(Camera2d);
30
31    commands
32        .spawn(Node {
33            width: percent(100.),
34            height: percent(100.),
35            justify_content: JustifyContent::Center,
36            align_items: AlignItems::Center,
37            ..default()
38        })
39        .with_children(|parent| {
40            parent
41                .spawn((
42                    Node {
43                        flex_direction: FlexDirection::Column,
44                        align_items: AlignItems::End,
45                        row_gap: px(10.),
46                        ..default()
47                    },
48                    TabGroup::default(),
49                ))
50                .with_children(|parent| {
51                    parent
52                        .spawn((
53                            Node {
54                                width: px(450.),
55                                border: px(2.).all(),
56                                padding: px(8.).all(),
57                                ..default()
58                            },
59                            EditableText {
60                                visible_lines: Some(8.),
61                                allow_newlines: true,
62                                ..default()
63                            },
64                            TextLayout {
65                                linebreak: LineBreak::WordOrCharacter,
66                                ..default()
67                            },
68                            TextCursorStyle {
69                                color: Color::WHITE,
70                                selected_text_color: Some(Color::BLACK),
71                                ..default()
72                            },
73                            TextFont {
74                                font: asset_server.load("fonts/FiraMono-Medium.ttf").into(),
75                                font_size: FontSize::Px(30.),
76                                ..default()
77                            },
78                            BackgroundColor(DARK_SLATE_GRAY.into()),
79                            BorderColor::all(SLATE_300),
80                            MultilineInput,
81                            TabIndex(0),
82                            AutoFocus,
83                        ))
84                        .observe(
85                            |on: On<FocusedInput<KeyboardInput>>,
86                             keys: Res<ButtonInput<Key>>,
87                             input_query: Query<&EditableText, With<MultilineInput>>| {
88                                if !(on.input.state.is_pressed()
89                                    && on.input.logical_key == Key::Enter
90                                    && keys.pressed(Key::Control))
91                                {
92                                    return;
93                                }
94                                let Ok(input) = input_query.get(on.focused_entity) else {
95                                    return;
96                                };
97
98                                let mut output = String::new();
99                                output.reserve(input.value().into_iter().map(str::len).sum());
100                                for sub_str in input.value() {
101                                    output.push_str(sub_str);
102                                }
103
104                                info!("{output}"                                    );
105                            },
106                        );
107
108                    parent
109                        .spawn((
110                            Node {
111                                flex_direction: FlexDirection::Row,
112                                column_gap: px(10.),
113                                ..default()
114                            },
115                            children![
116                                (
117                                    Text::new("visible lines:"),
118                                    TextFont {
119                                        font: asset_server.load("fonts/FiraMono-Medium.ttf").into(),
120                                        font_size: FontSize::Px(30.),
121                                        ..default()
122                                    },
123                                ),
124                                (
125                                    Node {
126                                        width: px(100.),
127                                        border: px(2.).all(),
128                                        ..default()
129                                    },
130                                    TextFont {
131                                        font: asset_server.load("fonts/FiraMono-Medium.ttf").into(),
132                                        font_size: FontSize::Px(30.),
133                                        ..default()
134                                    },
135                                    TextLayout {
136                                        justify: Justify::End,
137                                        ..default()
138                                    },
139                                    BackgroundColor(DARK_SLATE_GRAY.into()),
140                                    BorderColor::all(SLATE_300),
141                                    EditableText::new("8"),
142                                    EditableTextFilter::new(|c| c.is_ascii_digit() || c == '.'),
143                                    TextCursorStyle {
144                                        color: Color::WHITE,
145                                        selected_text_color: Some(Color::BLACK),
146                                        unfocused_selection_color: Color::NONE,
147                                        ..default()
148                                    },
149                                    SelectAllOnFocus,
150                                    VisibleLinesInput,
151                                    TabIndex(1),
152                                )
153                            ],
154                        ))
155                        .observe(
156                            |on: On<FocusedInput<KeyboardInput>>,
157                             mut query_set: ParamSet<(
158                                Query<&EditableText, With<VisibleLinesInput>>,
159                                Query<&mut EditableText, With<MultilineInput>>,
160                            )>| {
161                                if !(on.input.state.is_pressed()
162                                    && on.input.logical_key == Key::Enter)
163                                {
164                                    return;
165                                }
166
167                                let visible_lines_query = query_set.p0();
168                                let Ok(input) = visible_lines_query.get(on.original_event_target())
169                                else {
170                                    return;
171                                };
172
173                                let mut output = String::new();
174                                output.reserve(input.value().into_iter().map(str::len).sum());
175                                for sub_str in input.value() {
176                                    output.push_str(sub_str);
177                                }
178
179                                let Ok(lines) = output.parse::<f32>() else {
180                                    return;
181                                };
182
183                                let mut multiline_query = query_set.p1();
184                                let Ok(mut multiline_input) = multiline_query.single_mut() else {
185                                    return;
186                                };
187
188                                multiline_input.visible_lines = Some(lines.clamp(1., 10.));
189                            },
190                        );
191
192                    parent
193                        .spawn((
194                            Node {
195                                flex_direction: FlexDirection::Row,
196                                column_gap: px(10.),
197                                ..default()
198                            },
199                            children![
200                                (
201                                    Text::new("font size:"),
202                                    TextFont {
203                                        font: asset_server.load("fonts/FiraMono-Medium.ttf").into(),
204                                        font_size: FontSize::Px(30.),
205                                        ..default()
206                                    },
207                                ),
208                                (
209                                    Node {
210                                        width: px(100.),
211                                        border: px(2.).all(),
212                                        ..default()
213                                    },
214                                    TextFont {
215                                        font: asset_server.load("fonts/FiraMono-Medium.ttf").into(),
216                                        font_size: FontSize::Px(30.),
217                                        ..default()
218                                    },
219                                    TextLayout {
220                                        justify: Justify::End,
221                                        ..default()
222                                    },
223                                    BackgroundColor(DARK_SLATE_GRAY.into()),
224                                    BorderColor::all(SLATE_300),
225                                    EditableText::new("30"),
226                                    EditableTextFilter::new(|c| c.is_ascii_digit()),
227                                    TextCursorStyle {
228                                        color: Color::WHITE,
229                                        selected_text_color: Some(Color::BLACK),
230                                        unfocused_selection_color: Color::NONE,
231                                        ..default()
232                                    },
233                                    SelectAllOnFocus,
234                                    FontSizeInput,
235                                    TabIndex(2),
236                                )
237                            ],
238                        ))
239                        .observe(
240                            |on: On<FocusedInput<KeyboardInput>>,
241                             font_size_input_query: Query<&EditableText, With<FontSizeInput>>,
242                             mut multiline_input_font: Single<
243                                &mut TextFont,
244                                With<MultilineInput>,
245                            >| {
246                                if !(on.input.state.is_pressed()
247                                    && on.input.logical_key == Key::Enter)
248                                {
249                                    return;
250                                }
251
252                                let Ok(input) =
253                                    font_size_input_query.get(on.original_event_target())
254                                else {
255                                    return;
256                                };
257
258                                let mut output = String::new();
259                                output.reserve(input.value().into_iter().map(str::len).sum());
260                                for sub_str in input.value() {
261                                    output.push_str(sub_str);
262                                }
263
264                                let Ok(font_size) = output.parse::<f32>() else {
265                                    return;
266                                };
267
268                                multiline_input_font.font_size =
269                                    FontSize::Px(font_size.clamp(5., 50.));
270                            },
271                        );
272                });
273        });
274}
1.0.0 · Source

pub fn reserve_exact(&mut self, additional: usize)

Available on non-no_global_oom_handling only.

Reserves the minimum capacity for at least additional bytes more than the current length. Unlike reserve, this will not deliberately over-allocate to speculatively avoid frequent allocations. After calling reserve_exact, capacity will be greater than or equal to self.len() + additional. Does nothing if the capacity is already sufficient.

§Panics

Panics if the new capacity exceeds isize::MAX bytes.

§Examples

Basic usage:

let mut s = String::new();

s.reserve_exact(10);

assert!(s.capacity() >= 10);

This might not actually increase the capacity:

let mut s = String::with_capacity(10);
s.push('a');
s.push('b');

// s now has a length of 2 and a capacity of at least 10
let capacity = s.capacity();
assert_eq!(2, s.len());
assert!(capacity >= 10);

// Since we already have at least an extra 8 capacity, calling this...
s.reserve_exact(8);

// ... doesn't actually increase.
assert_eq!(capacity, s.capacity());
1.57.0 · Source

pub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError>

Tries to reserve capacity for at least additional bytes more than the current length. The allocator may reserve more space to speculatively avoid frequent allocations. After calling try_reserve, capacity will be greater than or equal to self.len() + additional if it returns Ok(()). Does nothing if capacity is already sufficient. This method preserves the contents even if an error occurs.

§Errors

If the capacity overflows, or the allocator reports a failure, then an error is returned.

§Examples
use std::collections::TryReserveError;

fn process_data(data: &str) -> Result<String, TryReserveError> {
    let mut output = String::new();

    // Pre-reserve the memory, exiting if we can't
    output.try_reserve(data.len())?;

    // Now we know this can't OOM in the middle of our complex work
    output.push_str(data);

    Ok(output)
}
1.57.0 · Source

pub fn try_reserve_exact( &mut self, additional: usize, ) -> Result<(), TryReserveError>

Tries to reserve the minimum capacity for at least additional bytes more than the current length. Unlike try_reserve, this will not deliberately over-allocate to speculatively avoid frequent allocations. After calling try_reserve_exact, capacity will be greater than or equal to self.len() + additional if it returns Ok(()). Does nothing if the capacity is already sufficient.

Note that the allocator may give the collection more space than it requests. Therefore, capacity can not be relied upon to be precisely minimal. Prefer try_reserve if future insertions are expected.

§Errors

If the capacity overflows, or the allocator reports a failure, then an error is returned.

§Examples
use std::collections::TryReserveError;

fn process_data(data: &str) -> Result<String, TryReserveError> {
    let mut output = String::new();

    // Pre-reserve the memory, exiting if we can't
    output.try_reserve_exact(data.len())?;

    // Now we know this can't OOM in the middle of our complex work
    output.push_str(data);

    Ok(output)
}
1.0.0 · Source

pub fn shrink_to_fit(&mut self)

Available on non-no_global_oom_handling only.

Shrinks the capacity of this String to match its length.

§Examples
let mut s = String::from("foo");

s.reserve(100);
assert!(s.capacity() >= 100);

s.shrink_to_fit();
assert_eq!(3, s.capacity());
1.56.0 · Source

pub fn shrink_to(&mut self, min_capacity: usize)

Available on non-no_global_oom_handling only.

Shrinks the capacity of this String with a lower bound.

The capacity will remain at least as large as both the length and the supplied value.

If the current capacity is less than the lower limit, this is a no-op.

§Examples
let mut s = String::from("foo");

s.reserve(100);
assert!(s.capacity() >= 100);

s.shrink_to(10);
assert!(s.capacity() >= 10);
s.shrink_to(0);
assert!(s.capacity() >= 3);
1.0.0 · Source

pub fn push(&mut self, ch: char)

Available on non-no_global_oom_handling only.

Appends the given char to the end of this String.

§Panics

Panics if the new capacity exceeds isize::MAX bytes.

§Examples
let mut s = String::from("abc");

s.push('1');
s.push('2');
s.push('3');

assert_eq!("abc123", s);
Examples found in repository?
examples/ui/text/font_atlas_debug.rs (line 79)
65fn text_update_system(
66    mut state: ResMut<State>,
67    time: Res<Time>,
68    mut query: Query<&mut Text>,
69    mut seeded_rng: ResMut<SeededRng>,
70) {
71    if !state.timer.tick(time.delta()).just_finished() {
72        return;
73    }
74
75    for mut text in &mut query {
76        let c = seeded_rng.random::<u8>() as char;
77        let string = &mut **text;
78        if !string.contains(c) {
79            string.push(c);
80        }
81    }
82}
More examples
Hide additional examples
examples/3d/light_probe_blending.rs (line 665)
649fn set_help_text(app_status: &AppStatus, help_text_query: &mut Query<&mut Text, With<HelpText>>) {
650    for mut ui_text in help_text_query {
651        let mut help_text = String::new();
652        match app_status.camera_mode {
653            CameraMode::Orbit => {
654                help_text.push_str(
655                    "Click and drag to orbit the camera\nUse the mouse wheel to zoom the camera\n",
656                );
657            }
658            CameraMode::Free => {
659                help_text.push_str(
660                    "Click and drag to rotate the camera\nUse WASDEQ to move the camera\n",
661                );
662            }
663        }
664
665        help_text.push('\n');
666
667        if matches!(app_status.gizmos_enabled, GizmosEnabled::On) {
668            help_text.push_str(
669                "\
670Gizmos:
671Tan: Light probe bounds
672Red: Light probe falloff bounds
673Blue: Parallax correction bounds",
674            );
675        }
676
677        *ui_text = Text::new(help_text);
678    }
679}
1.0.0 (const: 1.87.0) · Source

pub const fn as_bytes(&self) -> &[u8]

Returns a byte slice of this String’s contents.

The inverse of this method is from_utf8.

§Examples
let s = String::from("hello");

assert_eq!(&[104, 101, 108, 108, 111], s.as_bytes());
Examples found in repository?
examples/asset/processing/asset_processing.rs (line 223)
216    async fn save(
217        &self,
218        writer: &mut Writer,
219        asset: SavedAsset<'_, '_, Self::Asset>,
220        _settings: &Self::Settings,
221        _asset_path: AssetPath<'_>,
222    ) -> Result<TextSettings, Self::Error> {
223        writer.write_all(asset.text.as_bytes()).await?;
224        Ok(TextSettings::default())
225    }
More examples
Hide additional examples
examples/asset/asset_saving_with_subassets.rs (line 191)
169    async fn save(
170        &self,
171        writer: &mut Writer,
172        asset: SavedAsset<'_, '_, Self::Asset>,
173        _settings: &Self::Settings,
174        _asset_path: AssetPath<'_>,
175    ) -> Result<(), Self::Error> {
176        let boxes = asset
177            .boxes
178            .iter()
179            .map(|handle| {
180                asset
181                    .get_labeled_by_id::<OneBox>(handle)
182                    .unwrap()
183                    .get()
184                    .clone()
185            })
186            .collect();
187
188        // Note: serializing to string isn't ideal since we can't do a streaming write, but this is
189        // fine for an example.
190        let serialized = ron::to_string(&SerializableManyBoxes { boxes })?;
191        writer.write_all(serialized.as_bytes()).await?;
192
193        Ok(())
194    }
examples/animation/animation_graph.rs (line 198)
151fn setup_assets_programmatically(
152    commands: &mut Commands,
153    asset_server: &mut AssetServer,
154    animation_graphs: &mut Assets<AnimationGraph>,
155    _save: bool,
156) {
157    // Create the nodes.
158    let mut animation_graph = AnimationGraph::new();
159    let blend_node = animation_graph.add_blend(0.5, animation_graph.root);
160    animation_graph.add_clip(
161        asset_server.load(GltfAssetLabel::Animation(0).from_asset("models/animated/Fox.glb")),
162        1.0,
163        animation_graph.root,
164    );
165    animation_graph.add_clip(
166        asset_server.load(GltfAssetLabel::Animation(1).from_asset("models/animated/Fox.glb")),
167        1.0,
168        blend_node,
169    );
170    animation_graph.add_clip(
171        asset_server.load(GltfAssetLabel::Animation(2).from_asset("models/animated/Fox.glb")),
172        1.0,
173        blend_node,
174    );
175
176    // If asked to save, do so.
177    #[cfg(not(target_arch = "wasm32"))]
178    if _save {
179        let animation_graph = animation_graph.clone();
180
181        IoTaskPool::get()
182            .spawn(async move {
183                use std::io::Write;
184
185                let animation_graph: SerializedAnimationGraph = animation_graph
186                    .try_into()
187                    .expect("The animation graph failed to convert to its serialized form");
188
189                let serialized_graph =
190                    ron::ser::to_string_pretty(&animation_graph, PrettyConfig::default())
191                        .expect("Failed to serialize the animation graph");
192                let mut animation_graph_writer = File::create(Path::join(
193                    &FileAssetReader::get_base_path(),
194                    Path::join(Path::new("assets"), Path::new(ANIMATION_GRAPH_PATH)),
195                ))
196                .expect("Failed to open the animation graph asset");
197                animation_graph_writer
198                    .write_all(serialized_graph.as_bytes())
199                    .expect("Failed to write the animation graph");
200            })
201            .detach();
202    }
203
204    // Add the graph.
205    let handle = animation_graphs.add(animation_graph);
206
207    // Save the assets in a resource.
208    commands.insert_resource(ExampleAnimationGraph(handle));
209}
examples/scene/world_serialization.rs (line 211)
166fn save_world_system(world: &mut World) {
167    let asset_server = world.resource::<AssetServer>().clone();
168    // The `TypeRegistry` resource contains information about all registered types (including components).
169    // This is used to construct worlds, so we'll want to ensure that we use the registry from the
170    // main world. To do this, we can simply clone the `AppTypeRegistry` resource.
171    let type_registry = world.resource::<AppTypeRegistry>().clone();
172
173    // Any ECS World can be serialized.
174    // For demonstration purposes, we'll create a new one.
175    let mut scene_world = World::new();
176
177    let mut component_b = ComponentB::from_world(world);
178    component_b.value = "hello".to_string();
179    scene_world.spawn((
180        component_b,
181        ComponentA { x: 1.0, y: 2.0 },
182        Transform::IDENTITY,
183        Name::new("joe"),
184        WorldAssetRoot(asset_server.load("models/FlightHelmet/FlightHelmet.gltf#Scene0")),
185    ));
186    scene_world.spawn(ComponentA { x: 3.0, y: 4.0 });
187    scene_world.insert_resource(ResourceA { score: 1 });
188
189    // With our sample world ready to go, we can now create a DynamicWorld from it.
190    // For simplicity, we will create our scene using DynamicWorld directly, but if
191    // you need more control, you can use DynamicWorldBuilder.
192    let dynamic_world = DynamicWorld::from_world_with(&scene_world, &type_registry.read());
193
194    // Dynamic Worlds can be serialized like this:
195    let type_registry = world.resource::<AppTypeRegistry>();
196    let type_registry = type_registry.read();
197    let serialized_world = dynamic_world.serialize(&type_registry).unwrap();
198
199    // Shows the serialized world in the console
200    info!("{}", serialized_world);
201
202    // Writing the world to a new file. Using a task to avoid calling the filesystem APIs in a system
203    // as they are blocking.
204    //
205    // This can't work in Wasm as there is no filesystem access.
206    #[cfg(not(target_arch = "wasm32"))]
207    IoTaskPool::get()
208        .spawn(async move {
209            // Write the world RON data to file
210            File::create(format!("assets/{NEW_WORLD_FILE_PATH}"))
211                .and_then(|mut file| file.write(serialized_world.as_bytes()))
212                .expect("Error while writing world to file");
213        })
214        .detach();
215}
1.0.0 · Source

pub fn truncate(&mut self, new_len: usize)

Shortens this String to the specified length.

If new_len is greater than or equal to the string’s current length, this has no effect.

Note that this method has no effect on the allocated capacity of the string

§Panics

Panics if new_len does not lie on a char boundary.

§Examples
let mut s = String::from("hello");

s.truncate(2);

assert_eq!("he", s);
1.0.0 · Source

pub fn pop(&mut self) -> Option<char>

Removes the last character from the string buffer and returns it.

Returns None if this String is empty.

§Examples
let mut s = String::from("abč");

assert_eq!(s.pop(), Some('č'));
assert_eq!(s.pop(), Some('b'));
assert_eq!(s.pop(), Some('a'));

assert_eq!(s.pop(), None);
1.0.0 · Source

pub fn remove(&mut self, idx: usize) -> char

Removes a char from this String at byte position idx and returns it.

Copies all bytes after the removed char to new positions.

Note that calling this in a loop can result in quadratic behavior.

§Panics

Panics if idx is larger than or equal to the String’s length, or if it does not lie on a char boundary.

§Examples
let mut s = String::from("abç");

assert_eq!(s.remove(0), 'a');
assert_eq!(s.remove(1), 'ç');
assert_eq!(s.remove(0), 'b');
Source

pub fn remove_matches<P>(&mut self, pat: P)
where P: Pattern,

🔬This is a nightly-only experimental API. (string_remove_matches)
Available on non-no_global_oom_handling only.

Remove all matches of pattern pat in the String.

§Examples
#![feature(string_remove_matches)]
let mut s = String::from("Trees are not green, the sky is not blue.");
s.remove_matches("not ");
assert_eq!("Trees are green, the sky is blue.", s);

Matches will be detected and removed iteratively, so in cases where patterns overlap, only the first pattern will be removed:

#![feature(string_remove_matches)]
let mut s = String::from("banana");
s.remove_matches("ana");
assert_eq!("bna", s);
1.26.0 · Source

pub fn retain<F>(&mut self, f: F)
where F: FnMut(char) -> bool,

Retains only the characters specified by the predicate.

In other words, remove all characters c such that f(c) returns false. This method operates in place, visiting each character exactly once in the original order, and preserves the order of the retained characters.

§Examples
let mut s = String::from("f_o_ob_ar");

s.retain(|c| c != '_');

assert_eq!(s, "foobar");

Because the elements are visited exactly once in the original order, external state may be used to decide which elements to keep.

let mut s = String::from("abcde");
let keep = [false, true, true, false, true];
let mut iter = keep.iter();
s.retain(|_| *iter.next().unwrap());
assert_eq!(s, "bce");
1.0.0 · Source

pub fn insert(&mut self, idx: usize, ch: char)

Available on non-no_global_oom_handling only.

Inserts a character into this String at byte position idx.

Reallocates if self.capacity() is insufficient, which may involve copying all self.capacity() bytes. Makes space for the insertion by copying all bytes of &self[idx..] to new positions.

Note that calling this in a loop can result in quadratic behavior.

§Panics

Panics if idx is larger than the String’s length, or if it does not lie on a char boundary.

§Examples
let mut s = String::with_capacity(3);

s.insert(0, 'f');
s.insert(1, 'o');
s.insert(2, 'o');

assert_eq!("foo", s);
1.16.0 · Source

pub fn insert_str(&mut self, idx: usize, string: &str)

Available on non-no_global_oom_handling only.

Inserts a string slice into this String at byte position idx.

Reallocates if self.capacity() is insufficient, which may involve copying all self.capacity() bytes. Makes space for the insertion by copying all bytes of &self[idx..] to new positions.

Note that calling this in a loop can result in quadratic behavior.

§Panics

Panics if idx is larger than the String’s length, or if it does not lie on a char boundary.

§Examples
let mut s = String::from("bar");

s.insert_str(0, "foo");

assert_eq!("foobar", s);
1.0.0 (const: 1.87.0) · Source

pub const unsafe fn as_mut_vec(&mut self) -> &mut Vec<u8>

Returns a mutable reference to the contents of this String.

§Safety

This function is unsafe because the returned &mut Vec allows writing bytes which are not valid UTF-8. If this constraint is violated, using the original String after dropping the &mut Vec may violate memory safety, as the rest of the standard library assumes that Strings are valid UTF-8.

§Examples
let mut s = String::from("hello");

unsafe {
    let vec = s.as_mut_vec();
    assert_eq!(&[104, 101, 108, 108, 111][..], &vec[..]);

    vec.reverse();
}
assert_eq!(s, "olleh");
1.0.0 (const: 1.87.0) · Source

pub const fn len(&self) -> usize

Returns the length of this String, in bytes, not chars or graphemes. In other words, it might not be what a human considers the length of the string.

§Examples
let a = String::from("foo");
assert_eq!(a.len(), 3);

let fancy_f = String::from("ƒoo");
assert_eq!(fancy_f.len(), 4);
assert_eq!(fancy_f.chars().count(), 3);
Examples found in repository?
examples/3d/tonemapping.rs (line 419)
395fn update_ui(
396    mut text_query: Single<&mut Text, Without<SceneNumber>>,
397    settings: Single<(&Tonemapping, &ColorGrading)>,
398    current_scene: Res<CurrentScene>,
399    selected_parameter: Res<SelectedParameter>,
400    mut hide_ui: Local<bool>,
401    keys: Res<ButtonInput<KeyCode>>,
402) {
403    if keys.just_pressed(KeyCode::KeyH) {
404        *hide_ui = !*hide_ui;
405    }
406
407    if *hide_ui {
408        if !text_query.is_empty() {
409            // single_mut() always triggers change detection,
410            // so only access if text actually needs changing
411            text_query.clear();
412        }
413        return;
414    }
415
416    let (tonemapping, color_grading) = *settings;
417    let tonemapping = *tonemapping;
418
419    let mut text = String::with_capacity(text_query.len());
420
421    let scn = current_scene.0;
422    text.push_str("(H) Hide UI\n\n");
423    text.push_str("Test Scene: \n");
424    text.push_str(&format!(
425        "(Q) {} Basic Scene\n",
426        if scn == 1 { ">" } else { "" }
427    ));
428    text.push_str(&format!(
429        "(W) {} Color Sweep\n",
430        if scn == 2 { ">" } else { "" }
431    ));
432    text.push_str(&format!(
433        "(E) {} Image Viewer\n",
434        if scn == 3 { ">" } else { "" }
435    ));
436
437    text.push_str("\n\nTonemapping Method:\n");
438    text.push_str(&format!(
439        "(1) {} Disabled\n",
440        if tonemapping == Tonemapping::None {
441            ">"
442        } else {
443            ""
444        }
445    ));
446    text.push_str(&format!(
447        "(2) {} Reinhard\n",
448        if tonemapping == Tonemapping::Reinhard {
449            "> "
450        } else {
451            ""
452        }
453    ));
454    text.push_str(&format!(
455        "(3) {} Reinhard Luminance\n",
456        if tonemapping == Tonemapping::ReinhardLuminance {
457            ">"
458        } else {
459            ""
460        }
461    ));
462    text.push_str(&format!(
463        "(4) {} ACES Fitted\n",
464        if tonemapping == Tonemapping::AcesFitted {
465            ">"
466        } else {
467            ""
468        }
469    ));
470    text.push_str(&format!(
471        "(5) {} AgX\n",
472        if tonemapping == Tonemapping::AgX {
473            ">"
474        } else {
475            ""
476        }
477    ));
478    text.push_str(&format!(
479        "(6) {} SomewhatBoringDisplayTransform\n",
480        if tonemapping == Tonemapping::SomewhatBoringDisplayTransform {
481            ">"
482        } else {
483            ""
484        }
485    ));
486    text.push_str(&format!(
487        "(7) {} TonyMcMapface\n",
488        if tonemapping == Tonemapping::TonyMcMapface {
489            ">"
490        } else {
491            ""
492        }
493    ));
494    text.push_str(&format!(
495        "(8) {} Blender Filmic\n",
496        if tonemapping == Tonemapping::BlenderFilmic {
497            ">"
498        } else {
499            ""
500        }
501    ));
502    text.push_str(&format!(
503        "(9) {} Khronos PBR Neutral\n",
504        if tonemapping == Tonemapping::KhronosPbrNeutral {
505            ">"
506        } else {
507            ""
508        }
509    ));
510
511    text.push_str("\n\nColor Grading:\n");
512    text.push_str("(arrow keys)\n");
513    if selected_parameter.value == 0 {
514        text.push_str("> ");
515    }
516    text.push_str(&format!("Exposure: {:.2}\n", color_grading.global.exposure));
517    if selected_parameter.value == 1 {
518        text.push_str("> ");
519    }
520    text.push_str(&format!("Gamma: {:.2}\n", color_grading.shadows.gamma));
521    if selected_parameter.value == 2 {
522        text.push_str("> ");
523    }
524    text.push_str(&format!(
525        "PreSaturation: {:.2}\n",
526        color_grading.shadows.saturation
527    ));
528    if selected_parameter.value == 3 {
529        text.push_str("> ");
530    }
531    text.push_str(&format!(
532        "PostSaturation: {:.2}\n",
533        color_grading.global.post_saturation
534    ));
535    text.push_str("(Space) Reset all to default\n");
536
537    if current_scene.0 == 1 {
538        text.push_str("(Enter) Reset all to scene recommendation\n");
539    }
540
541    if text != text_query.as_str() {
542        // single_mut() always triggers change detection,
543        // so only access if text actually changed
544        text_query.0 = text;
545    }
546}
1.0.0 (const: 1.87.0) · Source

pub const fn is_empty(&self) -> bool

Returns true if this String has a length of zero, and false otherwise.

§Examples
let mut v = String::new();
assert!(v.is_empty());

v.push('a');
assert!(!v.is_empty());
Examples found in repository?
examples/3d/tonemapping.rs (line 408)
395fn update_ui(
396    mut text_query: Single<&mut Text, Without<SceneNumber>>,
397    settings: Single<(&Tonemapping, &ColorGrading)>,
398    current_scene: Res<CurrentScene>,
399    selected_parameter: Res<SelectedParameter>,
400    mut hide_ui: Local<bool>,
401    keys: Res<ButtonInput<KeyCode>>,
402) {
403    if keys.just_pressed(KeyCode::KeyH) {
404        *hide_ui = !*hide_ui;
405    }
406
407    if *hide_ui {
408        if !text_query.is_empty() {
409            // single_mut() always triggers change detection,
410            // so only access if text actually needs changing
411            text_query.clear();
412        }
413        return;
414    }
415
416    let (tonemapping, color_grading) = *settings;
417    let tonemapping = *tonemapping;
418
419    let mut text = String::with_capacity(text_query.len());
420
421    let scn = current_scene.0;
422    text.push_str("(H) Hide UI\n\n");
423    text.push_str("Test Scene: \n");
424    text.push_str(&format!(
425        "(Q) {} Basic Scene\n",
426        if scn == 1 { ">" } else { "" }
427    ));
428    text.push_str(&format!(
429        "(W) {} Color Sweep\n",
430        if scn == 2 { ">" } else { "" }
431    ));
432    text.push_str(&format!(
433        "(E) {} Image Viewer\n",
434        if scn == 3 { ">" } else { "" }
435    ));
436
437    text.push_str("\n\nTonemapping Method:\n");
438    text.push_str(&format!(
439        "(1) {} Disabled\n",
440        if tonemapping == Tonemapping::None {
441            ">"
442        } else {
443            ""
444        }
445    ));
446    text.push_str(&format!(
447        "(2) {} Reinhard\n",
448        if tonemapping == Tonemapping::Reinhard {
449            "> "
450        } else {
451            ""
452        }
453    ));
454    text.push_str(&format!(
455        "(3) {} Reinhard Luminance\n",
456        if tonemapping == Tonemapping::ReinhardLuminance {
457            ">"
458        } else {
459            ""
460        }
461    ));
462    text.push_str(&format!(
463        "(4) {} ACES Fitted\n",
464        if tonemapping == Tonemapping::AcesFitted {
465            ">"
466        } else {
467            ""
468        }
469    ));
470    text.push_str(&format!(
471        "(5) {} AgX\n",
472        if tonemapping == Tonemapping::AgX {
473            ">"
474        } else {
475            ""
476        }
477    ));
478    text.push_str(&format!(
479        "(6) {} SomewhatBoringDisplayTransform\n",
480        if tonemapping == Tonemapping::SomewhatBoringDisplayTransform {
481            ">"
482        } else {
483            ""
484        }
485    ));
486    text.push_str(&format!(
487        "(7) {} TonyMcMapface\n",
488        if tonemapping == Tonemapping::TonyMcMapface {
489            ">"
490        } else {
491            ""
492        }
493    ));
494    text.push_str(&format!(
495        "(8) {} Blender Filmic\n",
496        if tonemapping == Tonemapping::BlenderFilmic {
497            ">"
498        } else {
499            ""
500        }
501    ));
502    text.push_str(&format!(
503        "(9) {} Khronos PBR Neutral\n",
504        if tonemapping == Tonemapping::KhronosPbrNeutral {
505            ">"
506        } else {
507            ""
508        }
509    ));
510
511    text.push_str("\n\nColor Grading:\n");
512    text.push_str("(arrow keys)\n");
513    if selected_parameter.value == 0 {
514        text.push_str("> ");
515    }
516    text.push_str(&format!("Exposure: {:.2}\n", color_grading.global.exposure));
517    if selected_parameter.value == 1 {
518        text.push_str("> ");
519    }
520    text.push_str(&format!("Gamma: {:.2}\n", color_grading.shadows.gamma));
521    if selected_parameter.value == 2 {
522        text.push_str("> ");
523    }
524    text.push_str(&format!(
525        "PreSaturation: {:.2}\n",
526        color_grading.shadows.saturation
527    ));
528    if selected_parameter.value == 3 {
529        text.push_str("> ");
530    }
531    text.push_str(&format!(
532        "PostSaturation: {:.2}\n",
533        color_grading.global.post_saturation
534    ));
535    text.push_str("(Space) Reset all to default\n");
536
537    if current_scene.0 == 1 {
538        text.push_str("(Enter) Reset all to scene recommendation\n");
539    }
540
541    if text != text_query.as_str() {
542        // single_mut() always triggers change detection,
543        // so only access if text actually changed
544        text_query.0 = text;
545    }
546}
More examples
Hide additional examples
examples/ecs/dynamic.rs (line 84)
69fn main() {
70    let mut world = World::new();
71    let mut lines = std::io::stdin().lines();
72    let mut component_names = HashMap::<String, ComponentId>::new();
73    let mut component_info = HashMap::<ComponentId, ComponentInfo>::new();
74    let mut event_names = HashMap::<String, EventKey>::new();
75
76    println!("{PROMPT}");
77    loop {
78        print!("\n> ");
79        let _ = std::io::stdout().flush();
80        let Some(Ok(line)) = lines.next() else {
81            return;
82        };
83
84        if line.is_empty() {
85            return;
86        };
87
88        let Some((first, rest)) = line.trim().split_once(|c: char| c.is_whitespace()) else {
89            match &line.chars().next() {
90                Some('c') => println!("{COMPONENT_PROMPT}"),
91                Some('s') => println!("{ENTITY_PROMPT}"),
92                Some('q') => println!("{QUERY_PROMPT}"),
93                Some('e') => println!("{EVENT_PROMPT}"),
94                Some('t') => println!("{EMIT_PROMPT}"),
95                _ => println!("{PROMPT}"),
96            }
97            continue;
98        };
99
100        match &first[0..1] {
101            "c" => {
102                rest.split(',').for_each(|component| {
103                    let mut component = component.split_whitespace();
104                    let Some(name) = component.next() else {
105                        return;
106                    };
107                    let size = match component.next().map(str::parse) {
108                        Some(Ok(size)) => size,
109                        _ => 0,
110                    };
111                    // Register our new component to the world with a layout specified by it's size
112                    // SAFETY: [u64] is Send + Sync
113                    let id = world.register_component_with_descriptor(unsafe {
114                        ComponentDescriptor::new_with_layout(
115                            name.to_string(),
116                            StorageType::Table,
117                            Layout::array::<u64>(size).unwrap(),
118                            None,
119                            true,
120                            ComponentCloneBehavior::Default,
121                            None,
122                        )
123                    });
124                    let Some(info) = world.components().get_info(id) else {
125                        return;
126                    };
127                    component_names.insert(name.to_string(), id);
128                    component_info.insert(id, info.clone());
129                    println!("Component {} created with id: {}", name, id.index());
130                });
131            }
132            "s" => {
133                let mut to_insert_ids = Vec::new();
134                let mut to_insert_data = Vec::new();
135                rest.split(',').for_each(|component| {
136                    let mut component = component.split_whitespace();
137                    let Some(name) = component.next() else {
138                        return;
139                    };
140
141                    // Get the id for the component with the given name
142                    let Some(&id) = component_names.get(name) else {
143                        println!("Component {name} does not exist");
144                        return;
145                    };
146
147                    // Calculate the length for the array based on the layout created for this component id
148                    let info = world.components().get_info(id).unwrap();
149                    let len = info.layout().size() / size_of::<u64>();
150                    let mut values: Vec<u64> = component
151                        .take(len)
152                        .filter_map(|value| value.parse::<u64>().ok())
153                        .collect();
154                    values.resize(len, 0);
155
156                    // Collect the id and array to be inserted onto our entity
157                    to_insert_ids.push(id);
158                    to_insert_data.push(values);
159                });
160
161                let mut entity = world.spawn_empty();
162
163                // Construct an `OwningPtr` for each component in `to_insert_data`
164                let to_insert_ptr = to_owning_ptrs(&mut to_insert_data);
165
166                // SAFETY:
167                // - Component ids have been taken from the same world
168                // - Each array is created to the layout specified in the world
169                unsafe {
170                    entity.insert_by_ids(&to_insert_ids, to_insert_ptr.into_iter());
171                }
172
173                println!("Entity spawned with id: {}", entity.id());
174            }
175            "q" => {
176                let mut builder = QueryBuilder::<FilteredEntityMut>::new(&mut world);
177                parse_query(rest, &mut builder, &component_names);
178                let mut query = builder.build();
179                query.iter_mut(&mut world).for_each(|filtered_entity| {
180                    let terms = filtered_entity
181                        .access()
182                        .try_iter_access()
183                        .unwrap()
184                        .map(|component_access| {
185                            let id = *component_access.index();
186                            let ptr = filtered_entity.get_by_id(id).unwrap();
187                            let info = component_info.get(&id).unwrap();
188                            let len = info.layout().size() / size_of::<u64>();
189
190                            // SAFETY:
191                            // - All components are created with layout [u64]
192                            // - len is calculated from the component descriptor
193                            let data = unsafe {
194                                std::slice::from_raw_parts_mut(
195                                    ptr.assert_unique().as_ptr().cast::<u64>(),
196                                    len,
197                                )
198                            };
199
200                            // If we have write access, increment each value once
201                            if matches!(component_access, ComponentAccessKind::Exclusive(_)) {
202                                data.iter_mut().for_each(|data| {
203                                    *data += 1;
204                                });
205                            }
206
207                            format!("{}: {:?}", info.name(), data[0..len].to_vec())
208                        })
209                        .collect::<Vec<_>>()
210                        .join(", ");
211
212                    println!("{}: {}", filtered_entity.id(), terms);
213                });
214            }
215            "e" => {
216                rest.split(',').for_each(|event| {
217                    let name = event.trim();
218                    if name.is_empty() {
219                        return;
220                    }
221
222                    // Register a ComponentId for this event, no Rust type needed.
223                    // SAFETY: ZST with no drop
224                    let event_component_id = world.register_component_with_descriptor(unsafe {
225                        ComponentDescriptor::new_with_layout(
226                            format!("event:{name}"),
227                            StorageType::Table,
228                            Layout::new::<()>(),
229                            None,
230                            false,
231                            ComponentCloneBehavior::Ignore,
232                            None,
233                        )
234                    });
235                    // SAFETY: event_component_id was just registered for this event
236                    let event_key = unsafe { EventKey::new(event_component_id) };
237                    event_names.insert(name.to_string(), event_key);
238
239                    // Build a dynamic observer that prints when the event fires.
240                    let runner: ObserverRunner = |mut world, _observer, ctx, _event, _trigger| {
241                        println!("  Observer fired!");
242                        if let Some(mut counts) = world.get_resource_mut::<EventFireCount>() {
243                            *counts.0.entry(ctx.event_key).or_insert(0) += 1;
244                        }
245                    };
246
247                    // SAFETY: event_key was just registered, runner ignores pointers
248                    let observer =
249                        unsafe { Observer::with_dynamic_runner(runner).with_event_key(event_key) };
250                    world.spawn(observer);
251
252                    println!(
253                        "Event '{name}' registered (key: {}) with a dynamic observer",
254                        event_component_id.index()
255                    );
256                });
257
258                // Ensure the counter resource exists.
259                world.init_resource::<EventFireCount>();
260            }
261            "t" => {
262                let name = rest.trim();
263                let Some(&event_key) = event_names.get(name) else {
264                    println!(
265                        "Event '{name}' does not exist. Register it first with 'event {name}'"
266                    );
267                    continue;
268                };
269
270                let mut event_data = ();
271                let mut trigger_data = ();
272                // SAFETY: event_key was registered in this world, both pointers are valid ZSTs
273                unsafe {
274                    world.trigger_dynamic(
275                        event_key,
276                        PtrMut::from(&mut event_data),
277                        PtrMut::from(&mut trigger_data),
278                    );
279                }
280
281                let count = world
282                    .get_resource::<EventFireCount>()
283                    .map_or(0, |c| c.0.get(&event_key).copied().unwrap_or(0));
284                println!("Event '{name}' triggered ({count} fires)");
285            }
286            _ => continue,
287        }
288    }
289}
1.16.0 · Source

pub fn split_off(&mut self, at: usize) -> String

Available on non-no_global_oom_handling only.

Splits the string into two at the given byte index.

Returns a newly allocated String. self contains bytes [0, at), and the returned String contains bytes [at, len). at must be on the boundary of a UTF-8 code point.

Note that the capacity of self does not change.

§Panics

Panics if at is not on a UTF-8 code point boundary, or if it is beyond the last code point of the string.

§Examples
let mut hello = String::from("Hello, World!");
let world = hello.split_off(7);
assert_eq!(hello, "Hello, ");
assert_eq!(world, "World!");
1.0.0 · Source

pub fn clear(&mut self)

Truncates this String, removing all contents.

While this means the String will have a length of zero, it does not touch its capacity.

§Examples
let mut s = String::from("foo");

s.clear();

assert!(s.is_empty());
assert_eq!(0, s.len());
assert_eq!(3, s.capacity());
Examples found in repository?
examples/stress_tests/many_text.rs (line 212)
209fn update_lorem_text(mut lorem_text_query: Query<(&mut Text, &mut Lorem)>) {
210    for (mut text, mut lorem) in &mut lorem_text_query {
211        if lorem.0 {
212            text.0.clear();
213            text.0.push_str(LOREM_TEXT_1);
214        } else {
215            text.0.clear();
216            text.0.push_str(LOREM_TEXT_2);
217        }
218
219        lorem.0 = !lorem.0;
220    }
221}
More examples
Hide additional examples
examples/math/bounding_2d.rs (line 80)
75fn update_text(mut text: Single<&mut Text>, cur_state: Res<State<Test>>) {
76    if !cur_state.is_changed() {
77        return;
78    }
79
80    text.clear();
81
82    text.push_str("Intersection test:\n");
83    use Test::*;
84    for &test in &[AabbSweep, CircleSweep, RayCast, AabbCast, CircleCast] {
85        let s = if **cur_state == test { "*" } else { " " };
86        text.push_str(&format!(" {s} {test:?} {s}\n"));
87    }
88    text.push_str("\nPress space to cycle");
89}
examples/shader_advanced/fullscreen_material.rs (line 104)
93fn toggle_effect(
94    mut text: Single<&mut Text>,
95    keys: Res<ButtonInput<KeyCode>>,
96    camera: Single<(Entity, Option<&FullscreenEffect>), With<Camera3d>>,
97    mut commands: Commands,
98) {
99    if keys.just_pressed(KeyCode::KeyT) {
100        let (entity, effect) = *camera;
101
102        if effect.is_some() {
103            commands.entity(entity).remove::<FullscreenEffect>();
104            text.clear();
105            text.push_str("(T) FullscreenEffect: Off");
106        } else {
107            commands.entity(entity).insert(FullscreenEffect::new(0.0));
108            text.clear();
109            text.push_str("(T) FullscreenEffect: On");
110        }
111    }
112}
examples/ui/text/multiple_text_inputs.rs (line 190)
177fn synchronize_output_text(
178    changed_inputs: Query<(&EditableText, &TextInputRow), Changed<EditableText>>,
179    mut outputs: Query<(&mut Text, &TextInputRow), With<TextOutput>>,
180) {
181    for (editable_text, input_row) in &changed_inputs {
182        for (mut text, output_row) in &mut outputs {
183            if output_row.0 == input_row.0 {
184                // `EditableText::value()` returns a `SplitString` because Parley may keep IME preedit text
185                // in a contiguous range of the editor’s internal `String` buffer during composition.
186                // The returned `SplitString` omits that preedit range, exposing only the text before and after it.
187                //
188                // To avoid allocating a new `String`, we reserve the total length of the `SplitString`'s slices,
189                // then append them to the output `Text`.
190                text.0.clear();
191                text.0
192                    .reserve(editable_text.value().into_iter().map(str::len).sum());
193                for sub_str in editable_text.value() {
194                    text.0.push_str(sub_str);
195                }
196            }
197        }
198    }
199}
200
201// Submit the focused input's text when Enter is pressed.
202fn submit_text(
203    mut input_focus: ResMut<InputFocus>,
204    keyboard_input: Res<ButtonInput<Key>>,
205    mut text_input: Query<(&mut EditableText, &TextInputRow)>,
206    mut text_output: Query<(&mut Text, &TextInputRow), With<SubmitOutput>>,
207    tab_navigation: TabNavigation,
208) {
209    if keyboard_input.just_pressed(Key::Enter)
210        && let Some(focused_entity) = input_focus.get()
211        && let Ok((mut editable_text, input_row)) = text_input.get_mut(focused_entity)
212    {
213        for (mut text, output_row) in &mut text_output {
214            if input_row.0 == output_row.0 {
215                text.0.clear();
216                text.0
217                    .reserve(editable_text.value().into_iter().map(str::len).sum());
218                for sub_str in editable_text.value() {
219                    text.0.push_str(sub_str);
220                }
221                break;
222            }
223        }
224        editable_text.clear();
225
226        if let Ok(next) = tab_navigation.navigate(&input_focus, NavAction::Next) {
227            input_focus.set(next, FocusCause::Navigated);
228        }
229    }
230}
examples/3d/post_processing.rs (line 271)
270fn update_help_text(mut text: Single<&mut Text>, app_settings: Res<AppSettings>) {
271    text.clear();
272    let text_list = [
273        format!(
274            "Chromatic aberration intensity: {:.2}\n",
275            app_settings.chromatic_aberration_intensity
276        ),
277        format!(
278            "Vignette intensity: {:.2}\n",
279            app_settings.vignette_intensity
280        ),
281        format!("Vignette radius: {:.2}\n", app_settings.vignette_radius),
282        format!(
283            "Vignette smoothness: {:.2}\n",
284            app_settings.vignette_smoothness
285        ),
286        format!(
287            "Vignette roundness: {:.2}\n",
288            app_settings.vignette_roundness
289        ),
290        format!(
291            "Vignette edge_compensation: {:.2}\n",
292            app_settings.vignette_edge_compensation
293        ),
294        format!(
295            "Lens Distortion intensity: {:.2}\n",
296            app_settings.lens_distortion_intensity
297        ),
298        format!(
299            "Lens Distortion multiplier x: {:.2}\n",
300            app_settings.lens_distortion_multiplier_x
301        ),
302        format!(
303            "Lens Distortion multiplier y: {:.2}\n",
304            app_settings.lens_distortion_multiplier_y
305        ),
306    ];
307    for (i, val) in text_list.iter().enumerate() {
308        if i == app_settings.selected {
309            text.push_str("> ");
310        }
311        text.push_str(val);
312    }
313    text.push_str("\n(Press Up or Down to select)\n(Press Left or Right to change)");
314}
examples/3d/solari.rs (line 538)
528fn update_control_text(
529    mut text: Single<&mut Text, With<ControlText>>,
530    robot_light_material: Option<Res<RobotLightMaterial>>,
531    materials: Res<Assets<StandardMaterial>>,
532    directional_light: Query<Entity, With<DirectionalLight>>,
533    time: Res<Time<Virtual>>,
534    #[cfg(all(feature = "dlss", not(feature = "force_disable_dlss")))] dlss_rr_supported: Option<
535        Res<DlssRayReconstructionSupported>,
536    >,
537) {
538    text.0.clear();
539
540    if time.is_paused() {
541        text.0.push_str("(Space): Resume");
542    } else {
543        text.0.push_str("(Space): Pause");
544    }
545
546    if directional_light.single().is_ok() {
547        text.0.push_str("\n(1): Disable directional light");
548    } else {
549        text.0.push_str("\n(1): Enable directional light");
550    }
551
552    match robot_light_material.and_then(|m| materials.get(&m.0)) {
553        Some(robot_light_material) if robot_light_material.emissive != LinearRgba::BLACK => {
554            text.0.push_str("\n(2): Disable robot emissive light");
555        }
556        _ => {
557            text.0.push_str("\n(2): Enable robot emissive light");
558        }
559    }
560
561    #[cfg(all(feature = "dlss", not(feature = "force_disable_dlss")))]
562    if dlss_rr_supported.is_some() {
563        text.0
564            .push_str("\nDenoising: DLSS Ray Reconstruction enabled");
565    } else {
566        text.0
567            .push_str("\nDenoising: DLSS Ray Reconstruction not supported");
568    }
569
570    #[cfg(any(not(feature = "dlss"), feature = "force_disable_dlss"))]
571    text.0
572        .push_str("\nDenoising: App not compiled with DLSS support");
573}
574
575#[derive(Component)]
576struct PerformanceText;
577
578fn update_performance_text(
579    mut text: Single<&mut Text, With<PerformanceText>>,
580    diagnostics: Res<DiagnosticsStore>,
581) {
582    text.0.clear();
583
584    let mut total = 0.0;
585    let mut add_diagnostic = |name: &str, path: &'static str| {
586        let path = DiagnosticPath::new(path);
587        if let Some(value) = diagnostics.get(&path).and_then(Diagnostic::smoothed) {
588            text.push_str(&format!("{name:17}  {value:.2} ms\n"));
589            total += value;
590        }
591    };
592
593    (add_diagnostic)(
594        "Light tiles",
595        "render/solari_lighting/presample_light_tiles/elapsed_gpu",
596    );
597    (add_diagnostic)(
598        "World cache",
599        "render/solari_lighting/world_cache/elapsed_gpu",
600    );
601    (add_diagnostic)(
602        "Direct lighting",
603        "render/solari_lighting/direct_lighting/elapsed_gpu",
604    );
605    (add_diagnostic)(
606        "Diffuse indirect",
607        "render/solari_lighting/diffuse_indirect_lighting/elapsed_gpu",
608    );
609    (add_diagnostic)(
610        "Specular indirect",
611        "render/solari_lighting/specular_indirect_lighting/elapsed_gpu",
612    );
613    (add_diagnostic)("DLSS-RR", "render/dlss_ray_reconstruction/elapsed_gpu");
614    text.push_str(&format!("{:17}  {total:.2} ms\n", "Total"));
615
616    if let Some(world_cache_active_cells_count) = diagnostics
617        .get(&DiagnosticPath::new(
618            "render/solari_lighting/world_cache_active_cells_count",
619        ))
620        .and_then(Diagnostic::smoothed)
621    {
622        text.push_str(&format!(
623            "\nWorld cache cells {} ({:.0}%)",
624            world_cache_active_cells_count as u32,
625            (world_cache_active_cells_count * 100.0) / (2u64.pow(20) as f64)
626        ));
627    }
628}
1.6.0 · Source

pub fn drain<R>(&mut self, range: R) -> Drain<'_>
where R: RangeBounds<usize>,

Removes the specified range from the string in bulk, returning all removed characters as an iterator.

The returned iterator keeps a mutable borrow on the string to optimize its implementation.

§Panics

Panics if the range has start_bound > end_bound, or, if the range is bounded on either end and does not lie on a char boundary.

§Leaking

If the returned iterator goes out of scope without being dropped (due to core::mem::forget, for example), the string may still contain a copy of any drained characters, or may have lost characters arbitrarily, including characters outside the range.

§Examples
let mut s = String::from("α is alpha, β is beta");
let beta_offset = s.find('β').unwrap_or(s.len());

// Remove the range up until the β from the string
let t: String = s.drain(..beta_offset).collect();
assert_eq!(t, "α is alpha, ");
assert_eq!(s, "β is beta");

// A full range clears the string, like `clear()` does
s.drain(..);
assert_eq!(s, "");
Source

pub fn into_chars(self) -> IntoChars

🔬This is a nightly-only experimental API. (string_into_chars)

Converts a String into an iterator over the chars of the string.

As a string consists of valid UTF-8, we can iterate through a string by char. This method returns such an iterator.

It’s important to remember that char represents a Unicode Scalar Value, and might not match your idea of what a ‘character’ is. Iteration over grapheme clusters may be what you actually want. That functionality is not provided by Rust’s standard library, check crates.io instead.

§Examples

Basic usage:

#![feature(string_into_chars)]

let word = String::from("goodbye");

let mut chars = word.into_chars();

assert_eq!(Some('g'), chars.next());
assert_eq!(Some('o'), chars.next());
assert_eq!(Some('o'), chars.next());
assert_eq!(Some('d'), chars.next());
assert_eq!(Some('b'), chars.next());
assert_eq!(Some('y'), chars.next());
assert_eq!(Some('e'), chars.next());

assert_eq!(None, chars.next());

Remember, chars might not match your intuition about characters:

#![feature(string_into_chars)]

let y = String::from("y̆");

let mut chars = y.into_chars();

assert_eq!(Some('y'), chars.next()); // not 'y̆'
assert_eq!(Some('\u{0306}'), chars.next());

assert_eq!(None, chars.next());
1.27.0 · Source

pub fn replace_range<R>(&mut self, range: R, replace_with: &str)
where R: RangeBounds<usize>,

Available on non-no_global_oom_handling only.

Removes the specified range in the string, and replaces it with the given string. The given string doesn’t need to be the same length as the range.

§Panics

Panics if the range has start_bound > end_bound, or, if the range is bounded on either end and does not lie on a char boundary.

§Examples
let mut s = String::from("α is alpha, β is beta");
let beta_offset = s.find('β').unwrap_or(s.len());

// Replace the range up until the β from the string
s.replace_range(..beta_offset, "Α is capital alpha; ");
assert_eq!(s, "Α is capital alpha; β is beta");
Source

pub fn replace_first<P>(&mut self, from: P, to: &str)
where P: Pattern,

🔬This is a nightly-only experimental API. (string_replace_in_place)
Available on non-no_global_oom_handling only.

Replaces the leftmost occurrence of a pattern with another string, in-place.

This method can be preferred over string = string.replacen(..., 1);, as it can use the String’s existing capacity to prevent a reallocation if sufficient space is available.

§Examples

Basic usage:

#![feature(string_replace_in_place)]

let mut s = String::from("Test Results: ❌❌❌");

// Replace the leftmost ❌ with a ✅
s.replace_first('❌', "✅");
assert_eq!(s, "Test Results: ✅❌❌");
Source

pub fn replace_last<P>(&mut self, from: P, to: &str)
where P: Pattern, <P as Pattern>::Searcher<'a>: for<'a> ReverseSearcher<'a>,

🔬This is a nightly-only experimental API. (string_replace_in_place)
Available on non-no_global_oom_handling only.

Replaces the rightmost occurrence of a pattern with another string, in-place.

§Examples

Basic usage:

#![feature(string_replace_in_place)]

let mut s = String::from("Test Results: ❌❌❌");

// Replace the rightmost ❌ with a ✅
s.replace_last('❌', "✅");
assert_eq!(s, "Test Results: ❌❌✅");
1.4.0 · Source

pub fn into_boxed_str(self) -> Box<str>

Available on non-no_global_oom_handling only.

Converts this String into a Box<str>.

Before doing the conversion, this method discards excess capacity like shrink_to_fit. Note that this call may reallocate and copy the bytes of the string.

§Examples
let s = String::from("hello");

let b = s.into_boxed_str();
1.72.0 · Source

pub fn leak<'a>(self) -> &'a mut str

Consumes and leaks the String, returning a mutable reference to the contents, &'a mut str.

The caller has free choice over the returned lifetime, including 'static. Indeed, this function is ideally used for data that lives for the remainder of the program’s life, as dropping the returned reference will cause a memory leak.

It does not reallocate or shrink the String, so the leaked allocation may include unused capacity that is not part of the returned slice. If you want to discard excess capacity, call into_boxed_str, and then Box::leak instead. However, keep in mind that trimming the capacity may result in a reallocation and copy.

§Examples
let x = String::from("bucket");
let static_ref: &'static mut str = x.leak();
assert_eq!(static_ref, "bucket");

Methods from Deref<Target = str>§

1.0.0 · Source

pub fn len(&self) -> usize

Returns the length of self.

This length is in bytes, not chars or graphemes. In other words, it might not be what a human considers the length of the string.

§Examples
let len = "foo".len();
assert_eq!(3, len);

assert_eq!("ƒoo".len(), 4); // fancy f!
assert_eq!("ƒoo".chars().count(), 3);
1.0.0 · Source

pub fn is_empty(&self) -> bool

Returns true if self has a length of zero bytes.

§Examples
let s = "";
assert!(s.is_empty());

let s = "not empty";
assert!(!s.is_empty());
1.9.0 · Source

pub fn is_char_boundary(&self, index: usize) -> bool

Checks that index-th byte is the first byte in a UTF-8 code point sequence or the end of the string.

The start and end of the string (when index == self.len()) are considered to be boundaries.

Returns false if index is greater than self.len().

§Examples
let s = "Löwe 老虎 Léopard";
assert!(s.is_char_boundary(0));
// start of `老`
assert!(s.is_char_boundary(6));
assert!(s.is_char_boundary(s.len()));

// second byte of `ö`
assert!(!s.is_char_boundary(2));

// third byte of `老`
assert!(!s.is_char_boundary(8));
1.91.0 · Source

pub fn floor_char_boundary(&self, index: usize) -> usize

Finds the closest x not exceeding index where is_char_boundary(x) is true.

This method can help you truncate a string so that it’s still valid UTF-8, but doesn’t exceed a given number of bytes. Note that this is done purely at the character level and can still visually split graphemes, even though the underlying characters aren’t split. For example, the emoji 🧑‍🔬 (scientist) could be split so that the string only includes 🧑 (person) instead.

§Examples
let s = "❤️🧡💛💚💙💜";
assert_eq!(s.len(), 26);
assert!(!s.is_char_boundary(13));

let closest = s.floor_char_boundary(13);
assert_eq!(closest, 10);
assert_eq!(&s[..closest], "❤️🧡");
1.91.0 · Source

pub fn ceil_char_boundary(&self, index: usize) -> usize

Finds the closest x not below index where is_char_boundary(x) is true.

If index is greater than the length of the string, this returns the length of the string.

This method is the natural complement to floor_char_boundary. See that method for more details.

§Examples
let s = "❤️🧡💛💚💙💜";
assert_eq!(s.len(), 26);
assert!(!s.is_char_boundary(13));

let closest = s.ceil_char_boundary(13);
assert_eq!(closest, 14);
assert_eq!(&s[..closest], "❤️🧡💛");
1.0.0 · Source

pub fn as_bytes(&self) -> &[u8]

Converts a string slice to a byte slice. To convert the byte slice back into a string slice, use the from_utf8 function.

§Examples
let bytes = "bors".as_bytes();
assert_eq!(b"bors", bytes);
1.20.0 · Source

pub unsafe fn as_bytes_mut(&mut self) -> &mut [u8]

Converts a mutable string slice to a mutable byte slice.

§Safety

The caller must ensure that the content of the slice is valid UTF-8 before the borrow ends and the underlying str is used.

Use of a str whose contents are not valid UTF-8 is undefined behavior.

§Examples

Basic usage:

let mut s = String::from("Hello");
let bytes = unsafe { s.as_bytes_mut() };

assert_eq!(b"Hello", bytes);

Mutability:

let mut s = String::from("🗻∈🌏");

unsafe {
    let bytes = s.as_bytes_mut();

    bytes[0] = 0xF0;
    bytes[1] = 0x9F;
    bytes[2] = 0x8D;
    bytes[3] = 0x94;
}

assert_eq!("🍔∈🌏", s);
1.0.0 · Source

pub fn as_ptr(&self) -> *const u8

Converts a string slice to a raw pointer.

As string slices are a slice of bytes, the raw pointer points to a u8. This pointer will be pointing to the first byte of the string slice.

The caller must ensure that the returned pointer is never written to. If you need to mutate the contents of the string slice, use as_mut_ptr.

§Examples
let s = "Hello";
let ptr = s.as_ptr();
1.36.0 · Source

pub fn as_mut_ptr(&mut self) -> *mut u8

Converts a mutable string slice to a raw pointer.

As string slices are a slice of bytes, the raw pointer points to a u8. This pointer will be pointing to the first byte of the string slice.

It is your responsibility to make sure that the string slice only gets modified in a way that it remains valid UTF-8.

1.20.0 · Source

pub fn get<I>(&self, i: I) -> Option<&<I as SliceIndex<str>>::Output>
where I: SliceIndex<str>,

Returns a subslice of str.

This is the non-panicking alternative to indexing the str. Returns None whenever equivalent indexing operation would panic.

§Examples
let v = String::from("🗻∈🌏");

assert_eq!(Some("🗻"), v.get(0..4));

// indices not on UTF-8 sequence boundaries
assert!(v.get(1..).is_none());
assert!(v.get(..8).is_none());

// out of bounds
assert!(v.get(..42).is_none());
1.20.0 · Source

pub fn get_mut<I>( &mut self, i: I, ) -> Option<&mut <I as SliceIndex<str>>::Output>
where I: SliceIndex<str>,

Returns a mutable subslice of str.

This is the non-panicking alternative to indexing the str. Returns None whenever equivalent indexing operation would panic.

§Examples
let mut v = String::from("hello");
// correct length
assert!(v.get_mut(0..5).is_some());
// out of bounds
assert!(v.get_mut(..42).is_none());
assert_eq!(Some("he"), v.get_mut(0..2).map(|v| &*v));

assert_eq!("hello", v);
{
    let s = v.get_mut(0..2);
    let s = s.map(|s| {
        s.make_ascii_uppercase();
        &*s
    });
    assert_eq!(Some("HE"), s);
}
assert_eq!("HEllo", v);
1.20.0 · Source

pub unsafe fn get_unchecked<I>(&self, i: I) -> &<I as SliceIndex<str>>::Output
where I: SliceIndex<str>,

Returns an unchecked subslice of str.

This is the unchecked alternative to indexing the str.

§Safety

Callers of this function are responsible that these preconditions are satisfied:

  • The starting index must not exceed the ending index;
  • Indexes must be within bounds of the original slice;
  • Indexes must lie on UTF-8 sequence boundaries.

Failing that, the returned string slice may reference invalid memory or violate the invariants communicated by the str type.

§Examples
let v = "🗻∈🌏";
unsafe {
    assert_eq!("🗻", v.get_unchecked(0..4));
    assert_eq!("∈", v.get_unchecked(4..7));
    assert_eq!("🌏", v.get_unchecked(7..11));
}
1.20.0 · Source

pub unsafe fn get_unchecked_mut<I>( &mut self, i: I, ) -> &mut <I as SliceIndex<str>>::Output
where I: SliceIndex<str>,

Returns a mutable, unchecked subslice of str.

This is the unchecked alternative to indexing the str.

§Safety

Callers of this function are responsible that these preconditions are satisfied:

  • The starting index must not exceed the ending index;
  • Indexes must be within bounds of the original slice;
  • Indexes must lie on UTF-8 sequence boundaries.

Failing that, the returned string slice may reference invalid memory or violate the invariants communicated by the str type.

§Examples
let mut v = String::from("🗻∈🌏");
unsafe {
    assert_eq!("🗻", v.get_unchecked_mut(0..4));
    assert_eq!("∈", v.get_unchecked_mut(4..7));
    assert_eq!("🌏", v.get_unchecked_mut(7..11));
}
1.0.0 · Source

pub unsafe fn slice_unchecked(&self, begin: usize, end: usize) -> &str

👎Deprecated since 1.29.0:

use get_unchecked(begin..end) instead

Creates a string slice from another string slice, bypassing safety checks.

This is generally not recommended, use with caution! For a safe alternative see str and Index.

This new slice goes from begin to end, including begin but excluding end.

To get a mutable string slice instead, see the slice_mut_unchecked method.

§Safety

Callers of this function are responsible that three preconditions are satisfied:

  • begin must not exceed end.
  • begin and end must be byte positions within the string slice.
  • begin and end must lie on UTF-8 sequence boundaries.
§Examples
let s = "Löwe 老虎 Léopard";

unsafe {
    assert_eq!("Löwe 老虎 Léopard", s.slice_unchecked(0, 21));
}

let s = "Hello, world!";

unsafe {
    assert_eq!("world", s.slice_unchecked(7, 12));
}
1.5.0 · Source

pub unsafe fn slice_mut_unchecked( &mut self, begin: usize, end: usize, ) -> &mut str

👎Deprecated since 1.29.0:

use get_unchecked_mut(begin..end) instead

Creates a string slice from another string slice, bypassing safety checks.

This is generally not recommended, use with caution! For a safe alternative see str and IndexMut.

This new slice goes from begin to end, including begin but excluding end.

To get an immutable string slice instead, see the slice_unchecked method.

§Safety

Callers of this function are responsible that three preconditions are satisfied:

  • begin must not exceed end.
  • begin and end must be byte positions within the string slice.
  • begin and end must lie on UTF-8 sequence boundaries.
1.4.0 · Source

pub fn split_at(&self, mid: usize) -> (&str, &str)

Divides one string slice into two at an index.

The argument, mid, should be a byte offset from the start of the string. It must also be on the boundary of a UTF-8 code point.

The two slices returned go from the start of the string slice to mid, and from mid to the end of the string slice.

To get mutable string slices instead, see the split_at_mut method.

§Panics

Panics if mid is not on a UTF-8 code point boundary, or if it is past the end of the last code point of the string slice. For a non-panicking alternative see split_at_checked.

§Examples
let s = "Per Martin-Löf";

let (first, last) = s.split_at(3);

assert_eq!("Per", first);
assert_eq!(" Martin-Löf", last);
1.4.0 · Source

pub fn split_at_mut(&mut self, mid: usize) -> (&mut str, &mut str)

Divides one mutable string slice into two at an index.

The argument, mid, should be a byte offset from the start of the string. It must also be on the boundary of a UTF-8 code point.

The two slices returned go from the start of the string slice to mid, and from mid to the end of the string slice.

To get immutable string slices instead, see the split_at method.

§Panics

Panics if mid is not on a UTF-8 code point boundary, or if it is past the end of the last code point of the string slice. For a non-panicking alternative see split_at_mut_checked.

§Examples
let mut s = "Per Martin-Löf".to_string();
{
    let (first, last) = s.split_at_mut(3);
    first.make_ascii_uppercase();
    assert_eq!("PER", first);
    assert_eq!(" Martin-Löf", last);
}
assert_eq!("PER Martin-Löf", s);
1.80.0 · Source

pub fn split_at_checked(&self, mid: usize) -> Option<(&str, &str)>

Divides one string slice into two at an index.

The argument, mid, should be a valid byte offset from the start of the string. It must also be on the boundary of a UTF-8 code point. The method returns None if that’s not the case.

The two slices returned go from the start of the string slice to mid, and from mid to the end of the string slice.

To get mutable string slices instead, see the split_at_mut_checked method.

§Examples
let s = "Per Martin-Löf";

let (first, last) = s.split_at_checked(3).unwrap();
assert_eq!("Per", first);
assert_eq!(" Martin-Löf", last);

assert_eq!(None, s.split_at_checked(13));  // Inside “ö”
assert_eq!(None, s.split_at_checked(16));  // Beyond the string length
1.80.0 · Source

pub fn split_at_mut_checked( &mut self, mid: usize, ) -> Option<(&mut str, &mut str)>

Divides one mutable string slice into two at an index.

The argument, mid, should be a valid byte offset from the start of the string. It must also be on the boundary of a UTF-8 code point. The method returns None if that’s not the case.

The two slices returned go from the start of the string slice to mid, and from mid to the end of the string slice.

To get immutable string slices instead, see the split_at_checked method.

§Examples
let mut s = "Per Martin-Löf".to_string();
if let Some((first, last)) = s.split_at_mut_checked(3) {
    first.make_ascii_uppercase();
    assert_eq!("PER", first);
    assert_eq!(" Martin-Löf", last);
}
assert_eq!("PER Martin-Löf", s);

assert_eq!(None, s.split_at_mut_checked(13));  // Inside “ö”
assert_eq!(None, s.split_at_mut_checked(16));  // Beyond the string length
1.0.0 · Source

pub fn chars(&self) -> Chars<'_>

Returns an iterator over the chars of a string slice.

As a string slice consists of valid UTF-8, we can iterate through a string slice by char. This method returns such an iterator.

It’s important to remember that char represents a Unicode Scalar Value, and might not match your idea of what a ‘character’ is. Iteration over grapheme clusters may be what you actually want. This functionality is not provided by Rust’s standard library, check crates.io instead.

§Examples

Basic usage:

let word = "goodbye";

let count = word.chars().count();
assert_eq!(7, count);

let mut chars = word.chars();

assert_eq!(Some('g'), chars.next());
assert_eq!(Some('o'), chars.next());
assert_eq!(Some('o'), chars.next());
assert_eq!(Some('d'), chars.next());
assert_eq!(Some('b'), chars.next());
assert_eq!(Some('y'), chars.next());
assert_eq!(Some('e'), chars.next());

assert_eq!(None, chars.next());

Remember, chars might not match your intuition about characters:

let y = "y̆";

let mut chars = y.chars();

assert_eq!(Some('y'), chars.next()); // not 'y̆'
assert_eq!(Some('\u{0306}'), chars.next());

assert_eq!(None, chars.next());
1.0.0 · Source

pub fn char_indices(&self) -> CharIndices<'_>

Returns an iterator over the chars of a string slice, and their positions.

As a string slice consists of valid UTF-8, we can iterate through a string slice by char. This method returns an iterator of both these chars, as well as their byte positions.

The iterator yields tuples. The position is first, the char is second.

§Examples

Basic usage:

let word = "goodbye";

let count = word.char_indices().count();
assert_eq!(7, count);

let mut char_indices = word.char_indices();

assert_eq!(Some((0, 'g')), char_indices.next());
assert_eq!(Some((1, 'o')), char_indices.next());
assert_eq!(Some((2, 'o')), char_indices.next());
assert_eq!(Some((3, 'd')), char_indices.next());
assert_eq!(Some((4, 'b')), char_indices.next());
assert_eq!(Some((5, 'y')), char_indices.next());
assert_eq!(Some((6, 'e')), char_indices.next());

assert_eq!(None, char_indices.next());

Remember, chars might not match your intuition about characters:

let yes = "y̆es";

let mut char_indices = yes.char_indices();

assert_eq!(Some((0, 'y')), char_indices.next()); // not (0, 'y̆')
assert_eq!(Some((1, '\u{0306}')), char_indices.next());

// note the 3 here - the previous character took up two bytes
assert_eq!(Some((3, 'e')), char_indices.next());
assert_eq!(Some((4, 's')), char_indices.next());

assert_eq!(None, char_indices.next());
1.0.0 · Source

pub fn bytes(&self) -> Bytes<'_>

Returns an iterator over the bytes of a string slice.

As a string slice consists of a sequence of bytes, we can iterate through a string slice by byte. This method returns such an iterator.

§Examples
let mut bytes = "bors".bytes();

assert_eq!(Some(b'b'), bytes.next());
assert_eq!(Some(b'o'), bytes.next());
assert_eq!(Some(b'r'), bytes.next());
assert_eq!(Some(b's'), bytes.next());

assert_eq!(None, bytes.next());
1.1.0 · Source

pub fn split_whitespace(&self) -> SplitWhitespace<'_>

Splits a string slice by whitespace.

The iterator returned will return string slices that are sub-slices of the original string slice, separated by any amount of whitespace.

‘Whitespace’ is defined according to the terms of the Unicode Derived Core Property White_Space. If you only want to split on ASCII whitespace instead, use split_ascii_whitespace.

§Examples

Basic usage:

let mut iter = "A few words".split_whitespace();

assert_eq!(Some("A"), iter.next());
assert_eq!(Some("few"), iter.next());
assert_eq!(Some("words"), iter.next());

assert_eq!(None, iter.next());

All kinds of whitespace are considered:

let mut iter = " Mary   had\ta\u{2009}little  \n\t lamb".split_whitespace();
assert_eq!(Some("Mary"), iter.next());
assert_eq!(Some("had"), iter.next());
assert_eq!(Some("a"), iter.next());
assert_eq!(Some("little"), iter.next());
assert_eq!(Some("lamb"), iter.next());

assert_eq!(None, iter.next());

If the string is empty or all whitespace, the iterator yields no string slices:

assert_eq!("".split_whitespace().next(), None);
assert_eq!("   ".split_whitespace().next(), None);
1.34.0 · Source

pub fn split_ascii_whitespace(&self) -> SplitAsciiWhitespace<'_>

Splits a string slice by ASCII whitespace.

The iterator returned will return string slices that are sub-slices of the original string slice, separated by any amount of ASCII whitespace.

This uses the same definition as char::is_ascii_whitespace. To split by Unicode Whitespace instead, use split_whitespace. Note that because of this difference in definition, even if s.is_ascii() is true, s.split_ascii_whitespace() behavior will differ from s.split_whitespace() if s contains U+000B VERTICAL TAB.

§Examples

Basic usage:

let mut iter = "A few words".split_ascii_whitespace();

assert_eq!(Some("A"), iter.next());
assert_eq!(Some("few"), iter.next());
assert_eq!(Some("words"), iter.next());

assert_eq!(None, iter.next());

Various kinds of ASCII whitespace are considered (see char::is_ascii_whitespace):

let mut iter = " Mary   had\ta little  \n\t lamb".split_ascii_whitespace();
assert_eq!(Some("Mary"), iter.next());
assert_eq!(Some("had"), iter.next());
assert_eq!(Some("a"), iter.next());
assert_eq!(Some("little"), iter.next());
assert_eq!(Some("lamb"), iter.next());

assert_eq!(None, iter.next());

If the string is empty or all ASCII whitespace, the iterator yields no string slices:

assert_eq!("".split_ascii_whitespace().next(), None);
assert_eq!("   ".split_ascii_whitespace().next(), None);
1.0.0 · Source

pub fn lines(&self) -> Lines<'_>

Returns an iterator over the lines of a string, as string slices.

Lines are split at line endings that are either newlines (\n) or sequences of a carriage return followed by a line feed (\r\n).

Line terminators are not included in the lines returned by the iterator.

Note that any carriage return (\r) not immediately followed by a line feed (\n) does not split a line. These carriage returns are thereby included in the produced lines.

The final line ending is optional. A string that ends with a final line ending will return the same lines as an otherwise identical string without a final line ending.

An empty string returns an empty iterator.

§Examples

Basic usage:

let text = "foo\r\nbar\n\nbaz\r";
let mut lines = text.lines();

assert_eq!(Some("foo"), lines.next());
assert_eq!(Some("bar"), lines.next());
assert_eq!(Some(""), lines.next());
// Trailing carriage return is included in the last line
assert_eq!(Some("baz\r"), lines.next());

assert_eq!(None, lines.next());

The final line does not require any ending:

let text = "foo\nbar\n\r\nbaz";
let mut lines = text.lines();

assert_eq!(Some("foo"), lines.next());
assert_eq!(Some("bar"), lines.next());
assert_eq!(Some(""), lines.next());
assert_eq!(Some("baz"), lines.next());

assert_eq!(None, lines.next());

An empty string returns an empty iterator:

let text = "";
let mut lines = text.lines();

assert_eq!(lines.next(), None);
1.0.0 · Source

pub fn lines_any(&self) -> LinesAny<'_>

👎Deprecated since 1.4.0:

use lines() instead now

Returns an iterator over the lines of a string.

1.8.0 · Source

pub fn encode_utf16(&self) -> EncodeUtf16<'_>

Returns an iterator of u16 over the string encoded as native endian UTF-16 (without byte-order mark).

§Examples
let text = "Zażółć gęślą jaźń";

let utf8_len = text.len();
let utf16_len = text.encode_utf16().count();

assert!(utf16_len <= utf8_len);
1.0.0 · Source

pub fn contains<P>(&self, pat: P) -> bool
where P: Pattern,

Returns true if the given pattern matches a sub-slice of this string slice.

Returns false if it does not.

The pattern can be a &str, char, a slice of chars, or a function or closure that determines if a character matches.

§Examples
let bananas = "bananas";

assert!(bananas.contains("nana"));
assert!(!bananas.contains("apples"));
1.0.0 · Source

pub fn starts_with<P>(&self, pat: P) -> bool
where P: Pattern,

Returns true if the given pattern matches a prefix of this string slice.

Returns false if it does not.

The pattern can be a &str, in which case this function will return true if the &str is a prefix of this string slice.

The pattern can also be a char, a slice of chars, or a function or closure that determines if a character matches. These will only be checked against the first character of this string slice. Look at the second example below regarding behavior for slices of chars.

§Examples
let bananas = "bananas";

assert!(bananas.starts_with("bana"));
assert!(!bananas.starts_with("nana"));
let bananas = "bananas";

// Note that both of these assert successfully.
assert!(bananas.starts_with(&['b', 'a', 'n', 'a']));
assert!(bananas.starts_with(&['a', 'b', 'c', 'd']));
1.0.0 · Source

pub fn ends_with<P>(&self, pat: P) -> bool
where P: Pattern, <P as Pattern>::Searcher<'a>: for<'a> ReverseSearcher<'a>,

Returns true if the given pattern matches a suffix of this string slice.

Returns false if it does not.

The pattern can be a &str, char, a slice of chars, or a function or closure that determines if a character matches.

§Examples
let bananas = "bananas";

assert!(bananas.ends_with("anas"));
assert!(!bananas.ends_with("nana"));
1.0.0 · Source

pub fn find<P>(&self, pat: P) -> Option<usize>
where P: Pattern,

Returns the byte index of the first character of this string slice that matches the pattern.

Returns None if the pattern doesn’t match.

The pattern can be a &str, char, a slice of chars, or a function or closure that determines if a character matches.

§Examples

Simple patterns:

let s = "Löwe 老虎 Léopard Gepardi";

assert_eq!(s.find('L'), Some(0));
assert_eq!(s.find('é'), Some(14));
assert_eq!(s.find("pard"), Some(17));

More complex patterns using point-free style and closures:

let s = "Löwe 老虎 Léopard";

assert_eq!(s.find(char::is_whitespace), Some(5));
assert_eq!(s.find(char::is_lowercase), Some(1));
assert_eq!(s.find(|c: char| c.is_whitespace() || c.is_lowercase()), Some(1));
assert_eq!(s.find(|c: char| (c < 'o') && (c > 'a')), Some(4));

Not finding the pattern:

let s = "Löwe 老虎 Léopard";
let x: &[_] = &['1', '2'];

assert_eq!(s.find(x), None);
1.0.0 · Source

pub fn rfind<P>(&self, pat: P) -> Option<usize>
where P: Pattern, <P as Pattern>::Searcher<'a>: for<'a> ReverseSearcher<'a>,

Returns the byte index for the first character of the last match of the pattern in this string slice.

Returns None if the pattern doesn’t match.

The pattern can be a &str, char, a slice of chars, or a function or closure that determines if a character matches.

§Examples

Simple patterns:

let s = "Löwe 老虎 Léopard Gepardi";

assert_eq!(s.rfind('L'), Some(13));
assert_eq!(s.rfind('é'), Some(14));
assert_eq!(s.rfind("pard"), Some(24));

More complex patterns with closures:

let s = "Löwe 老虎 Léopard";

assert_eq!(s.rfind(char::is_whitespace), Some(12));
assert_eq!(s.rfind(char::is_lowercase), Some(20));

Not finding the pattern:

let s = "Löwe 老虎 Léopard";
let x: &[_] = &['1', '2'];

assert_eq!(s.rfind(x), None);
1.0.0 · Source

pub fn split<P>(&self, pat: P) -> Split<'_, P>
where P: Pattern,

Returns an iterator over substrings of this string slice, separated by characters matched by a pattern.

The pattern can be a &str, char, a slice of chars, or a function or closure that determines if a character matches.

If there are no matches the full string slice is returned as the only item in the iterator.

§Iterator behavior

The returned iterator will be a DoubleEndedIterator if the pattern allows a reverse search and forward/reverse search yields the same elements. This is true for, e.g., char, but not for &str.

If the pattern allows a reverse search but its results might differ from a forward search, the rsplit method can be used.

§Examples

Simple patterns:

let v: Vec<&str> = "Mary had a little lamb".split(' ').collect();
assert_eq!(v, ["Mary", "had", "a", "little", "lamb"]);

let v: Vec<&str> = "".split('X').collect();
assert_eq!(v, [""]);

let v: Vec<&str> = "lionXXtigerXleopard".split('X').collect();
assert_eq!(v, ["lion", "", "tiger", "leopard"]);

let v: Vec<&str> = "lion::tiger::leopard".split("::").collect();
assert_eq!(v, ["lion", "tiger", "leopard"]);

let v: Vec<&str> = "AABBCC".split("DD").collect();
assert_eq!(v, ["AABBCC"]);

let v: Vec<&str> = "abc1def2ghi".split(char::is_numeric).collect();
assert_eq!(v, ["abc", "def", "ghi"]);

let v: Vec<&str> = "lionXtigerXleopard".split(char::is_uppercase).collect();
assert_eq!(v, ["lion", "tiger", "leopard"]);

If the pattern is a slice of chars, split on each occurrence of any of the characters:

let v: Vec<&str> = "2020-11-03 23:59".split(&['-', ' ', ':', '@'][..]).collect();
assert_eq!(v, ["2020", "11", "03", "23", "59"]);

A more complex pattern, using a closure:

let v: Vec<&str> = "abc1defXghi".split(|c| c == '1' || c == 'X').collect();
assert_eq!(v, ["abc", "def", "ghi"]);

If a string contains multiple contiguous separators, you will end up with empty strings in the output:

let x = "||||a||b|c".to_string();
let d: Vec<_> = x.split('|').collect();

assert_eq!(d, &["", "", "", "", "a", "", "b", "c"]);

Contiguous separators are separated by the empty string.

let x = "(///)".to_string();
let d: Vec<_> = x.split('/').collect();

assert_eq!(d, &["(", "", "", ")"]);

Separators at the start or end of a string are neighbored by empty strings.

let d: Vec<_> = "010".split("0").collect();
assert_eq!(d, &["", "1", ""]);

When the empty string is used as a separator, it separates every character in the string, along with the beginning and end of the string.

let f: Vec<_> = "rust".split("").collect();
assert_eq!(f, &["", "r", "u", "s", "t", ""]);

Contiguous separators can lead to possibly surprising behavior when whitespace is used as the separator. This code is correct:

let x = "    a  b c".to_string();
let d: Vec<_> = x.split(' ').collect();

assert_eq!(d, &["", "", "", "", "a", "", "b", "c"]);

It does not give you:

assert_eq!(d, &["a", "b", "c"]);

Use split_whitespace for this behavior.

1.51.0 · Source

pub fn split_inclusive<P>(&self, pat: P) -> SplitInclusive<'_, P>
where P: Pattern,

Returns an iterator over substrings of this string slice, separated by characters matched by a pattern.

Differs from the iterator produced by split in that split_inclusive leaves the matched part as the terminator of the substring.

The pattern can be a &str, char, a slice of chars, or a function or closure that determines if a character matches.

§Examples
let v: Vec<&str> = "Mary had a little lamb\nlittle lamb\nlittle lamb."
    .split_inclusive('\n').collect();
assert_eq!(v, ["Mary had a little lamb\n", "little lamb\n", "little lamb."]);

If the last element of the string is matched, that element will be considered the terminator of the preceding substring. That substring will be the last item returned by the iterator.

let v: Vec<&str> = "Mary had a little lamb\nlittle lamb\nlittle lamb.\n"
    .split_inclusive('\n').collect();
assert_eq!(v, ["Mary had a little lamb\n", "little lamb\n", "little lamb.\n"]);
1.0.0 · Source

pub fn rsplit<P>(&self, pat: P) -> RSplit<'_, P>
where P: Pattern, <P as Pattern>::Searcher<'a>: for<'a> ReverseSearcher<'a>,

Returns an iterator over substrings of the given string slice, separated by characters matched by a pattern and yielded in reverse order.

The pattern can be a &str, char, a slice of chars, or a function or closure that determines if a character matches.

§Iterator behavior

The returned iterator requires that the pattern supports a reverse search, and it will be a DoubleEndedIterator if a forward/reverse search yields the same elements.

For iterating from the front, the split method can be used.

§Examples

Simple patterns:

let v: Vec<&str> = "Mary had a little lamb".rsplit(' ').collect();
assert_eq!(v, ["lamb", "little", "a", "had", "Mary"]);

let v: Vec<&str> = "".rsplit('X').collect();
assert_eq!(v, [""]);

let v: Vec<&str> = "lionXXtigerXleopard".rsplit('X').collect();
assert_eq!(v, ["leopard", "tiger", "", "lion"]);

let v: Vec<&str> = "lion::tiger::leopard".rsplit("::").collect();
assert_eq!(v, ["leopard", "tiger", "lion"]);

A more complex pattern, using a closure:

let v: Vec<&str> = "abc1defXghi".rsplit(|c| c == '1' || c == 'X').collect();
assert_eq!(v, ["ghi", "def", "abc"]);
1.0.0 · Source

pub fn split_terminator<P>(&self, pat: P) -> SplitTerminator<'_, P>
where P: Pattern,

Returns an iterator over substrings of the given string slice, separated by characters matched by a pattern.

The pattern can be a &str, char, a slice of chars, or a function or closure that determines if a character matches.

Equivalent to split, except that the trailing substring is skipped if empty.

This method can be used for string data that is terminated, rather than separated by a pattern.

§Iterator behavior

The returned iterator will be a DoubleEndedIterator if the pattern allows a reverse search and forward/reverse search yields the same elements. This is true for, e.g., char, but not for &str.

If the pattern allows a reverse search but its results might differ from a forward search, the rsplit_terminator method can be used.

§Examples
let v: Vec<&str> = "A.B.".split_terminator('.').collect();
assert_eq!(v, ["A", "B"]);

let v: Vec<&str> = "A..B..".split_terminator(".").collect();
assert_eq!(v, ["A", "", "B", ""]);

let v: Vec<&str> = "A.B:C.D".split_terminator(&['.', ':'][..]).collect();
assert_eq!(v, ["A", "B", "C", "D"]);
1.0.0 · Source

pub fn rsplit_terminator<P>(&self, pat: P) -> RSplitTerminator<'_, P>
where P: Pattern, <P as Pattern>::Searcher<'a>: for<'a> ReverseSearcher<'a>,

Returns an iterator over substrings of self, separated by characters matched by a pattern and yielded in reverse order.

The pattern can be a &str, char, a slice of chars, or a function or closure that determines if a character matches.

Equivalent to split, except that the trailing substring is skipped if empty.

This method can be used for string data that is terminated, rather than separated by a pattern.

§Iterator behavior

The returned iterator requires that the pattern supports a reverse search, and it will be double ended if a forward/reverse search yields the same elements.

For iterating from the front, the split_terminator method can be used.

§Examples
let v: Vec<&str> = "A.B.".rsplit_terminator('.').collect();
assert_eq!(v, ["B", "A"]);

let v: Vec<&str> = "A..B..".rsplit_terminator(".").collect();
assert_eq!(v, ["", "B", "", "A"]);

let v: Vec<&str> = "A.B:C.D".rsplit_terminator(&['.', ':'][..]).collect();
assert_eq!(v, ["D", "C", "B", "A"]);
1.0.0 · Source

pub fn splitn<P>(&self, n: usize, pat: P) -> SplitN<'_, P>
where P: Pattern,

Returns an iterator over substrings of the given string slice, separated by a pattern, restricted to returning at most n items.

If n substrings are returned, the last substring (the nth substring) will contain the remainder of the string.

The pattern can be a &str, char, a slice of chars, or a function or closure that determines if a character matches.

§Iterator behavior

The returned iterator will not be double ended, because it is not efficient to support.

If the pattern allows a reverse search, the rsplitn method can be used.

§Examples

Simple patterns:

let v: Vec<&str> = "Mary had a little lambda".splitn(3, ' ').collect();
assert_eq!(v, ["Mary", "had", "a little lambda"]);

let v: Vec<&str> = "lionXXtigerXleopard".splitn(3, "X").collect();
assert_eq!(v, ["lion", "", "tigerXleopard"]);

let v: Vec<&str> = "abcXdef".splitn(1, 'X').collect();
assert_eq!(v, ["abcXdef"]);

let v: Vec<&str> = "".splitn(1, 'X').collect();
assert_eq!(v, [""]);

A more complex pattern, using a closure:

let v: Vec<&str> = "abc1defXghi".splitn(2, |c| c == '1' || c == 'X').collect();
assert_eq!(v, ["abc", "defXghi"]);
1.0.0 · Source

pub fn rsplitn<P>(&self, n: usize, pat: P) -> RSplitN<'_, P>
where P: Pattern, <P as Pattern>::Searcher<'a>: for<'a> ReverseSearcher<'a>,

Returns an iterator over substrings of this string slice, separated by a pattern, starting from the end of the string, restricted to returning at most n items.

If n substrings are returned, the last substring (the nth substring) will contain the remainder of the string.

The pattern can be a &str, char, a slice of chars, or a function or closure that determines if a character matches.

§Iterator behavior

The returned iterator will not be double ended, because it is not efficient to support.

For splitting from the front, the splitn method can be used.

§Examples

Simple patterns:

let v: Vec<&str> = "Mary had a little lamb".rsplitn(3, ' ').collect();
assert_eq!(v, ["lamb", "little", "Mary had a"]);

let v: Vec<&str> = "lionXXtigerXleopard".rsplitn(3, 'X').collect();
assert_eq!(v, ["leopard", "tiger", "lionX"]);

let v: Vec<&str> = "lion::tiger::leopard".rsplitn(2, "::").collect();
assert_eq!(v, ["leopard", "lion::tiger"]);

A more complex pattern, using a closure:

let v: Vec<&str> = "abc1defXghi".rsplitn(2, |c| c == '1' || c == 'X').collect();
assert_eq!(v, ["ghi", "abc1def"]);
1.52.0 · Source

pub fn split_once<P>(&self, delimiter: P) -> Option<(&str, &str)>
where P: Pattern,

Splits the string on the first occurrence of the specified delimiter and returns prefix before delimiter and suffix after delimiter.

§Examples
assert_eq!("cfg".split_once('='), None);
assert_eq!("cfg=".split_once('='), Some(("cfg", "")));
assert_eq!("cfg=foo".split_once('='), Some(("cfg", "foo")));
assert_eq!("cfg=foo=bar".split_once('='), Some(("cfg", "foo=bar")));
1.52.0 · Source

pub fn rsplit_once<P>(&self, delimiter: P) -> Option<(&str, &str)>
where P: Pattern, <P as Pattern>::Searcher<'a>: for<'a> ReverseSearcher<'a>,

Splits the string on the last occurrence of the specified delimiter and returns prefix before delimiter and suffix after delimiter.

§Examples
assert_eq!("cfg".rsplit_once('='), None);
assert_eq!("cfg=".rsplit_once('='), Some(("cfg", "")));
assert_eq!("cfg=foo".rsplit_once('='), Some(("cfg", "foo")));
assert_eq!("cfg=foo=bar".rsplit_once('='), Some(("cfg=foo", "bar")));
1.2.0 · Source

pub fn matches<P>(&self, pat: P) -> Matches<'_, P>
where P: Pattern,

Returns an iterator over the disjoint matches of a pattern within the given string slice.

The pattern can be a &str, char, a slice of chars, or a function or closure that determines if a character matches.

§Iterator behavior

The returned iterator will be a DoubleEndedIterator if the pattern allows a reverse search and forward/reverse search yields the same elements. This is true for, e.g., char, but not for &str.

If the pattern allows a reverse search but its results might differ from a forward search, the rmatches method can be used.

§Examples
let v: Vec<&str> = "abcXXXabcYYYabc".matches("abc").collect();
assert_eq!(v, ["abc", "abc", "abc"]);

let v: Vec<&str> = "1abc2abc3".matches(char::is_numeric).collect();
assert_eq!(v, ["1", "2", "3"]);
1.2.0 · Source

pub fn rmatches<P>(&self, pat: P) -> RMatches<'_, P>
where P: Pattern, <P as Pattern>::Searcher<'a>: for<'a> ReverseSearcher<'a>,

Returns an iterator over the disjoint matches of a pattern within this string slice, yielded in reverse order.

The pattern can be a &str, char, a slice of chars, or a function or closure that determines if a character matches.

§Iterator behavior

The returned iterator requires that the pattern supports a reverse search, and it will be a DoubleEndedIterator if a forward/reverse search yields the same elements.

For iterating from the front, the matches method can be used.

§Examples
let v: Vec<&str> = "abcXXXabcYYYabc".rmatches("abc").collect();
assert_eq!(v, ["abc", "abc", "abc"]);

let v: Vec<&str> = "1abc2abc3".rmatches(char::is_numeric).collect();
assert_eq!(v, ["3", "2", "1"]);
1.5.0 · Source

pub fn match_indices<P>(&self, pat: P) -> MatchIndices<'_, P>
where P: Pattern,

Returns an iterator over the disjoint matches of a pattern within this string slice as well as the index that the match starts at.

For matches of pat within self that overlap, only the indices corresponding to the first match are returned.

The pattern can be a &str, char, a slice of chars, or a function or closure that determines if a character matches.

§Iterator behavior

The returned iterator will be a DoubleEndedIterator if the pattern allows a reverse search and forward/reverse search yields the same elements. This is true for, e.g., char, but not for &str.

If the pattern allows a reverse search but its results might differ from a forward search, the rmatch_indices method can be used.

§Examples
let v: Vec<_> = "abcXXXabcYYYabc".match_indices("abc").collect();
assert_eq!(v, [(0, "abc"), (6, "abc"), (12, "abc")]);

let v: Vec<_> = "1abcabc2".match_indices("abc").collect();
assert_eq!(v, [(1, "abc"), (4, "abc")]);

let v: Vec<_> = "ababa".match_indices("aba").collect();
assert_eq!(v, [(0, "aba")]); // only the first `aba`
1.5.0 · Source

pub fn rmatch_indices<P>(&self, pat: P) -> RMatchIndices<'_, P>
where P: Pattern, <P as Pattern>::Searcher<'a>: for<'a> ReverseSearcher<'a>,

Returns an iterator over the disjoint matches of a pattern within self, yielded in reverse order along with the index of the match.

For matches of pat within self that overlap, only the indices corresponding to the last match are returned.

The pattern can be a &str, char, a slice of chars, or a function or closure that determines if a character matches.

§Iterator behavior

The returned iterator requires that the pattern supports a reverse search, and it will be a DoubleEndedIterator if a forward/reverse search yields the same elements.

For iterating from the front, the match_indices method can be used.

§Examples
let v: Vec<_> = "abcXXXabcYYYabc".rmatch_indices("abc").collect();
assert_eq!(v, [(12, "abc"), (6, "abc"), (0, "abc")]);

let v: Vec<_> = "1abcabc2".rmatch_indices("abc").collect();
assert_eq!(v, [(4, "abc"), (1, "abc")]);

let v: Vec<_> = "ababa".rmatch_indices("aba").collect();
assert_eq!(v, [(2, "aba")]); // only the last `aba`
1.0.0 · Source

pub fn trim(&self) -> &str

Returns a string slice with leading and trailing whitespace removed.

‘Whitespace’ is defined according to the terms of the Unicode Derived Core Property White_Space, which includes newlines.

§Examples
let s = "\n Hello\tworld\t\n";

assert_eq!("Hello\tworld", s.trim());
1.30.0 · Source

pub fn trim_start(&self) -> &str

Returns a string slice with leading whitespace removed.

‘Whitespace’ is defined according to the terms of the Unicode Derived Core Property White_Space, which includes newlines.

§Text directionality

A string is a sequence of bytes. start in this context means the first position of that byte string; for a left-to-right language like English or Russian, this will be left side, and for right-to-left languages like Arabic or Hebrew, this will be the right side.

§Examples

Basic usage:

let s = "\n Hello\tworld\t\n";
assert_eq!("Hello\tworld\t\n", s.trim_start());

Directionality:

let s = "  English  ";
assert!(Some('E') == s.trim_start().chars().next());

let s = "  עברית  ";
assert!(Some('ע') == s.trim_start().chars().next());
1.30.0 · Source

pub fn trim_end(&self) -> &str

Returns a string slice with trailing whitespace removed.

‘Whitespace’ is defined according to the terms of the Unicode Derived Core Property White_Space, which includes newlines.

§Text directionality

A string is a sequence of bytes. end in this context means the last position of that byte string; for a left-to-right language like English or Russian, this will be right side, and for right-to-left languages like Arabic or Hebrew, this will be the left side.

§Examples

Basic usage:

let s = "\n Hello\tworld\t\n";
assert_eq!("\n Hello\tworld", s.trim_end());

Directionality:

let s = "  English  ";
assert!(Some('h') == s.trim_end().chars().rev().next());

let s = "  עברית  ";
assert!(Some('ת') == s.trim_end().chars().rev().next());
1.0.0 · Source

pub fn trim_left(&self) -> &str

👎Deprecated since 1.33.0:

superseded by trim_start

Returns a string slice with leading whitespace removed.

‘Whitespace’ is defined according to the terms of the Unicode Derived Core Property White_Space.

§Text directionality

A string is a sequence of bytes. ‘Left’ in this context means the first position of that byte string; for a language like Arabic or Hebrew which are ‘right to left’ rather than ‘left to right’, this will be the right side, not the left.

§Examples

Basic usage:

let s = " Hello\tworld\t";

assert_eq!("Hello\tworld\t", s.trim_left());

Directionality:

let s = "  English";
assert!(Some('E') == s.trim_left().chars().next());

let s = "  עברית";
assert!(Some('ע') == s.trim_left().chars().next());
1.0.0 · Source

pub fn trim_right(&self) -> &str

👎Deprecated since 1.33.0:

superseded by trim_end

Returns a string slice with trailing whitespace removed.

‘Whitespace’ is defined according to the terms of the Unicode Derived Core Property White_Space.

§Text directionality

A string is a sequence of bytes. ‘Right’ in this context means the last position of that byte string; for a language like Arabic or Hebrew which are ‘right to left’ rather than ‘left to right’, this will be the left side, not the right.

§Examples

Basic usage:

let s = " Hello\tworld\t";

assert_eq!(" Hello\tworld", s.trim_right());

Directionality:

let s = "English  ";
assert!(Some('h') == s.trim_right().chars().rev().next());

let s = "עברית  ";
assert!(Some('ת') == s.trim_right().chars().rev().next());
1.0.0 · Source

pub fn trim_matches<P>(&self, pat: P) -> &str
where P: Pattern, <P as Pattern>::Searcher<'a>: for<'a> DoubleEndedSearcher<'a>,

Returns a string slice with all prefixes and suffixes that match a pattern repeatedly removed.

The pattern can be a char, a slice of chars, or a function or closure that determines if a character matches.

§Examples

Simple patterns:

assert_eq!("11foo1bar11".trim_matches('1'), "foo1bar");
assert_eq!("123foo1bar123".trim_matches(char::is_numeric), "foo1bar");

let x: &[_] = &['1', '2'];
assert_eq!("12foo1bar12".trim_matches(x), "foo1bar");

A more complex pattern, using a closure:

assert_eq!("1foo1barXX".trim_matches(|c| c == '1' || c == 'X'), "foo1bar");
1.30.0 · Source

pub fn trim_start_matches<P>(&self, pat: P) -> &str
where P: Pattern,

Returns a string slice with all prefixes that match a pattern repeatedly removed.

The pattern can be a &str, char, a slice of chars, or a function or closure that determines if a character matches.

§Text directionality

A string is a sequence of bytes. start in this context means the first position of that byte string; for a left-to-right language like English or Russian, this will be left side, and for right-to-left languages like Arabic or Hebrew, this will be the right side.

§Examples
assert_eq!("11foo1bar11".trim_start_matches('1'), "foo1bar11");
assert_eq!("123foo1bar123".trim_start_matches(char::is_numeric), "foo1bar123");

let x: &[_] = &['1', '2'];
assert_eq!("12foo1bar12".trim_start_matches(x), "foo1bar12");
1.45.0 · Source

pub fn strip_prefix<P>(&self, prefix: P) -> Option<&str>
where P: Pattern,

Returns a string slice with the prefix removed.

If the string starts with the pattern prefix, returns the substring after the prefix, wrapped in Some. Unlike trim_start_matches, this method removes the prefix exactly once.

If the string does not start with prefix, returns None.

The pattern can be a &str, char, a slice of chars, or a function or closure that determines if a character matches.

§Examples
assert_eq!("foo:bar".strip_prefix("foo:"), Some("bar"));
assert_eq!("foo:bar".strip_prefix("bar"), None);
assert_eq!("foofoo".strip_prefix("foo"), Some("foo"));
1.45.0 · Source

pub fn strip_suffix<P>(&self, suffix: P) -> Option<&str>
where P: Pattern, <P as Pattern>::Searcher<'a>: for<'a> ReverseSearcher<'a>,

Returns a string slice with the suffix removed.

If the string ends with the pattern suffix, returns the substring before the suffix, wrapped in Some. Unlike trim_end_matches, this method removes the suffix exactly once.

If the string does not end with suffix, returns None.

The pattern can be a &str, char, a slice of chars, or a function or closure that determines if a character matches.

§Examples
assert_eq!("bar:foo".strip_suffix(":foo"), Some("bar"));
assert_eq!("bar:foo".strip_suffix("bar"), None);
assert_eq!("foofoo".strip_suffix("foo"), Some("foo"));
1.98.0 · Source

pub fn strip_circumfix<P, S>(&self, prefix: P, suffix: S) -> Option<&str>
where P: Pattern, S: Pattern, <S as Pattern>::Searcher<'a>: for<'a> ReverseSearcher<'a>,

Returns a string slice with the prefix and suffix removed.

If the string starts with the pattern prefix and ends with the pattern suffix, and the prefix and suffix don’t overlap, returns the substring after the prefix and before the suffix, wrapped in Some. Unlike trim_start_matches and trim_end_matches, this method removes both the prefix and suffix exactly once.

If the string does not start with prefix, does not end with suffix, or the prefix and suffix overlap in the string, returns None.

Each pattern can be a &str, char, a slice of chars, or a function or closure that determines if a character matches.

§Examples
assert_eq!("bar:hello:foo".strip_circumfix("bar:", ":foo"), Some("hello"));
assert_eq!("bar:foo".strip_circumfix("foo", "foo"), None);
assert_eq!("foo:bar;".strip_circumfix("foo:", ';'), Some("bar"));
assert_eq!("foo:bar:baz".strip_circumfix("foo:bar:", ":bar:baz"), None);
Source

pub fn trim_prefix<P>(&self, prefix: P) -> &str
where P: Pattern,

🔬This is a nightly-only experimental API. (trim_prefix_suffix)

Returns a string slice with the optional prefix removed.

If the string starts with the pattern prefix, returns the substring after the prefix. Unlike strip_prefix, this method always returns &str for easy method chaining, instead of returning Option<&str>.

If the string does not start with prefix, returns the original string unchanged.

The pattern can be a &str, char, a slice of chars, or a function or closure that determines if a character matches.

§Examples
#![feature(trim_prefix_suffix)]

// Prefix present - removes it
assert_eq!("foo:bar".trim_prefix("foo:"), "bar");
assert_eq!("foofoo".trim_prefix("foo"), "foo");

// Prefix absent - returns original string
assert_eq!("foo:bar".trim_prefix("bar"), "foo:bar");

// Method chaining example
assert_eq!("<https://example.com/>".trim_prefix('<').trim_suffix('>'), "https://example.com/");
Source

pub fn trim_suffix<P>(&self, suffix: P) -> &str
where P: Pattern, <P as Pattern>::Searcher<'a>: for<'a> ReverseSearcher<'a>,

🔬This is a nightly-only experimental API. (trim_prefix_suffix)

Returns a string slice with the optional suffix removed.

If the string ends with the pattern suffix, returns the substring before the suffix. Unlike strip_suffix, this method always returns &str for easy method chaining, instead of returning Option<&str>.

If the string does not end with suffix, returns the original string unchanged.

The pattern can be a &str, char, a slice of chars, or a function or closure that determines if a character matches.

§Examples
#![feature(trim_prefix_suffix)]

// Suffix present - removes it
assert_eq!("bar:foo".trim_suffix(":foo"), "bar");
assert_eq!("foofoo".trim_suffix("foo"), "foo");

// Suffix absent - returns original string
assert_eq!("bar:foo".trim_suffix("bar"), "bar:foo");

// Method chaining example
assert_eq!("<https://example.com/>".trim_prefix('<').trim_suffix('>'), "https://example.com/");
1.30.0 · Source

pub fn trim_end_matches<P>(&self, pat: P) -> &str
where P: Pattern, <P as Pattern>::Searcher<'a>: for<'a> ReverseSearcher<'a>,

Returns a string slice with all suffixes that match a pattern repeatedly removed.

The pattern can be a &str, char, a slice of chars, or a function or closure that determines if a character matches.

§Text directionality

A string is a sequence of bytes. end in this context means the last position of that byte string; for a left-to-right language like English or Russian, this will be right side, and for right-to-left languages like Arabic or Hebrew, this will be the left side.

§Examples

Simple patterns:

assert_eq!("11foo1bar11".trim_end_matches('1'), "11foo1bar");
assert_eq!("123foo1bar123".trim_end_matches(char::is_numeric), "123foo1bar");

let x: &[_] = &['1', '2'];
assert_eq!("12foo1bar12".trim_end_matches(x), "12foo1bar");

A more complex pattern, using a closure:

assert_eq!("1fooX".trim_end_matches(|c| c == '1' || c == 'X'), "1foo");
1.0.0 · Source

pub fn trim_left_matches<P>(&self, pat: P) -> &str
where P: Pattern,

👎Deprecated since 1.33.0:

superseded by trim_start_matches

Returns a string slice with all prefixes that match a pattern repeatedly removed.

The pattern can be a &str, char, a slice of chars, or a function or closure that determines if a character matches.

§Text directionality

A string is a sequence of bytes. ‘Left’ in this context means the first position of that byte string; for a language like Arabic or Hebrew which are ‘right to left’ rather than ‘left to right’, this will be the right side, not the left.

§Examples
assert_eq!("11foo1bar11".trim_left_matches('1'), "foo1bar11");
assert_eq!("123foo1bar123".trim_left_matches(char::is_numeric), "foo1bar123");

let x: &[_] = &['1', '2'];
assert_eq!("12foo1bar12".trim_left_matches(x), "foo1bar12");
1.0.0 · Source

pub fn trim_right_matches<P>(&self, pat: P) -> &str
where P: Pattern, <P as Pattern>::Searcher<'a>: for<'a> ReverseSearcher<'a>,

👎Deprecated since 1.33.0:

superseded by trim_end_matches

Returns a string slice with all suffixes that match a pattern repeatedly removed.

The pattern can be a &str, char, a slice of chars, or a function or closure that determines if a character matches.

§Text directionality

A string is a sequence of bytes. ‘Right’ in this context means the last position of that byte string; for a language like Arabic or Hebrew which are ‘right to left’ rather than ‘left to right’, this will be the left side, not the right.

§Examples

Simple patterns:

assert_eq!("11foo1bar11".trim_right_matches('1'), "11foo1bar");
assert_eq!("123foo1bar123".trim_right_matches(char::is_numeric), "123foo1bar");

let x: &[_] = &['1', '2'];
assert_eq!("12foo1bar12".trim_right_matches(x), "12foo1bar");

A more complex pattern, using a closure:

assert_eq!("1fooX".trim_right_matches(|c| c == '1' || c == 'X'), "1foo");
1.0.0 · Source

pub fn parse<F>(&self) -> Result<F, <F as FromStr>::Err>
where F: FromStr,

Parses this string slice into another type.

Because parse is so general, it can cause problems with type inference. As such, parse is one of the few times you’ll see the syntax affectionately known as the ‘turbofish’: ::<>. This helps the inference algorithm understand specifically which type you’re trying to parse into.

parse can parse into any type that implements the FromStr trait.

§Errors

Will return Err if it’s not possible to parse this string slice into the desired type.

§Examples

Basic usage:

let four: u32 = "4".parse().unwrap();

assert_eq!(4, four);

Using the ‘turbofish’ instead of annotating four:

let four = "4".parse::<u32>();

assert_eq!(Ok(4), four);

Failing to parse:

let nope = "j".parse::<u32>();

assert!(nope.is_err());
1.23.0 · Source

pub fn is_ascii(&self) -> bool

Checks if all characters in this string are within the ASCII range.

An empty string returns true.

§Examples
let ascii = "hello!\n";
let non_ascii = "Grüße, Jürgen ❤";

assert!(ascii.is_ascii());
assert!(!non_ascii.is_ascii());
Source

pub fn as_ascii(&self) -> Option<&[AsciiChar]>

🔬This is a nightly-only experimental API. (ascii_char)

If this string slice is_ascii, returns it as a slice of ASCII characters, otherwise returns None.

Source

pub unsafe fn as_ascii_unchecked(&self) -> &[AsciiChar]

🔬This is a nightly-only experimental API. (ascii_char)

Converts this string slice into a slice of ASCII characters, without checking whether they are valid.

§Safety

Every character in this string must be ASCII, or else this is UB.

1.23.0 · Source

pub fn eq_ignore_ascii_case(&self, other: &str) -> bool

Checks that two strings are an ASCII case-insensitive match.

Same as to_ascii_lowercase(a) == to_ascii_lowercase(b), but without allocating and copying temporaries.

For Unicode-aware case-insensitive matching, consider str::eq_ignore_case_unnormalized.

§Examples
assert!("Ferris".eq_ignore_ascii_case("FERRIS"));
assert!("Ferrös".eq_ignore_ascii_case("FERRöS"));
assert!(!"Ferrös".eq_ignore_ascii_case("FERRÖS"));
Source

pub fn eq_ignore_case_unnormalized(&self, other: &str) -> bool

🔬This is a nightly-only experimental API. (casefold)

Checks that two strings are a caseless match, according to Definition 144 in Chapter 3 of the Unicode Standard.

Same as a.to_casefold_unnormalized() == b.to_casefold_unnormalized(), but without allocating. See that method’s documentation, as well as char::to_casefold_unnormalized(), for more information about case folding.

No normalization (e.g. NFC) is performed, so visually and semantically identical strings might still compare unequal. For example, "Å" (U+00C5 LATIN CAPITAL LETTER A WITH RING ABOVE) is considered distinct from "Å" (A followed by U+030A COMBINING RING ABOVE), even though Unicode considers them canonically equivalent.

In addition, this method is independent of language/locale, so the special behavior of I/ı/İ/i in Turkish and Azeri is not handled.

§Examples
#![feature(casefold)]
assert!("Ferris".eq_ignore_case_unnormalized("FERRIS"));
assert!("Ferrös".eq_ignore_case_unnormalized("FERRÖS"));
assert!("ẞ".eq_ignore_case_unnormalized("ss"));

No NFC normalization is performed:

#![feature(casefold)]
// These two strings are visually and semantically identical...
let comp = "Å";
let decomp = "Å";

// ... but not codepoint-for-codepoint equal.
assert_eq!(comp, "\u{C5}");
assert_eq!(decomp, "A\u{030A}");

// Their case-foldings are likewise unequal:
assert!(!comp.eq_ignore_case_unnormalized(decomp));
1.23.0 · Source

pub fn make_ascii_uppercase(&mut self)

Converts this string to its ASCII upper case equivalent in-place.

ASCII letters ‘a’ to ‘z’ are mapped to ‘A’ to ‘Z’, but non-ASCII letters are unchanged.

To return a new uppercased value without modifying the existing one, use to_ascii_uppercase().

§Examples
let mut s = String::from("Grüße, Jürgen ❤");

s.make_ascii_uppercase();

assert_eq!("GRüßE, JüRGEN ❤", s);
1.23.0 · Source

pub fn make_ascii_lowercase(&mut self)

Converts this string to its ASCII lower case equivalent in-place.

ASCII letters ‘A’ to ‘Z’ are mapped to ‘a’ to ‘z’, but non-ASCII letters are unchanged.

To return a new lowercased value without modifying the existing one, use to_ascii_lowercase().

§Examples
let mut s = String::from("GRÜßE, JÜRGEN ❤");

s.make_ascii_lowercase();

assert_eq!("grÜße, jÜrgen ❤", s);
Source

pub fn copy_from_str(&mut self, src: &str)

🔬This is a nightly-only experimental API. (str_copy_from_str)

Copies the string from src into self, using a memcpy.

The length of src must be the same as self.

§Panics

This function will panic if the two strings have different lengths.

§Examples
#![feature(str_copy_from_str)]
let src = "Saludos";
let mut dst = String::from("Grüße, Jürgen");

// Because the strings have to be the same length,
// we slice the destination slice from sixteen bytes
// to seven. It will panic if we don't do this.
dst[..7].copy_from_str(src);

assert_eq!(src, "Saludos");
assert_eq!(dst, "Saludos, Jürgen");

Rust enforces that there can only be one mutable reference with no immutable references to a particular piece of data in a particular scope. Because of this, attempting to use copy_from_str on a single string will result in a compile failure:

#![feature(str_copy_from_str)]
let mut string = String::from("Abcde");

string[..2].copy_from_str(&string[3..]); // compile fail!

To work around this, we can use split_at_mut to create two distinct sub-slices from a string:

#![feature(str_copy_from_str)]
let mut string = String::from("Abcde");

{
    let (left, right) = string.split_at_mut(2);
    left.copy_from_str(&right[1..]);
}

assert_eq!(string, "decde");
1.80.0 · Source

pub fn trim_ascii_start(&self) -> &str

Returns a string slice with leading ASCII whitespace removed.

‘Whitespace’ refers to the definition used by u8::is_ascii_whitespace. Importantly, this definition excludes the U+000B code point even though it has the Unicode White_Space property and is removed by str::trim_start.

§Examples
assert_eq!(" \t \u{3000}hello world\n".trim_ascii_start(), "\u{3000}hello world\n");
assert_eq!("  ".trim_ascii_start(), "");
assert_eq!("".trim_ascii_start(), "");
1.80.0 · Source

pub fn trim_ascii_end(&self) -> &str

Returns a string slice with trailing ASCII whitespace removed.

‘Whitespace’ refers to the definition used by u8::is_ascii_whitespace. Importantly, this definition excludes the U+000B code point even though it has the Unicode White_Space property and is removed by str::trim_end.

§Examples
assert_eq!("\r hello world\u{3000}\n ".trim_ascii_end(), "\r hello world\u{3000}");
assert_eq!("  ".trim_ascii_end(), "");
assert_eq!("".trim_ascii_end(), "");
1.80.0 · Source

pub fn trim_ascii(&self) -> &str

Returns a string slice with leading and trailing ASCII whitespace removed.

‘Whitespace’ refers to the definition used by u8::is_ascii_whitespace. Importantly, this definition excludes the U+000B code point even though it has the Unicode White_Space property and is removed by str::trim.

§Examples
assert_eq!("\r hello world\n ".trim_ascii(), "hello world");
assert_eq!("  ".trim_ascii(), "");
assert_eq!("".trim_ascii(), "");
1.34.0 · Source

pub fn escape_debug(&self) -> EscapeDebug<'_>

Returns an iterator that escapes each char in self with char::escape_debug.

Note: only extended grapheme codepoints that begin the string will be escaped.

§Examples

As an iterator:

for c in "❤\n!".escape_debug() {
    print!("{c}");
}
println!();

Using println! directly:

println!("{}", "❤\n!".escape_debug());

Both are equivalent to:

println!("❤\\n!");

Using to_string:

assert_eq!("❤\n!".escape_debug().to_string(), "❤\\n!");
1.34.0 · Source

pub fn escape_default(&self) -> EscapeDefault<'_>

Returns an iterator that escapes each char in self with char::escape_default.

§Examples

As an iterator:

for c in "❤\n!".escape_default() {
    print!("{c}");
}
println!();

Using println! directly:

println!("{}", "❤\n!".escape_default());

Both are equivalent to:

println!("\\u{{2764}}\\n!");

Using to_string:

assert_eq!("❤\n!".escape_default().to_string(), "\\u{2764}\\n!");
1.34.0 · Source

pub fn escape_unicode(&self) -> EscapeUnicode<'_>

Returns an iterator that escapes each char in self with char::escape_unicode.

§Examples

As an iterator:

for c in "❤\n!".escape_unicode() {
    print!("{c}");
}
println!();

Using println! directly:

println!("{}", "❤\n!".escape_unicode());

Both are equivalent to:

println!("\\u{{2764}}\\u{{a}}\\u{{21}}");

Using to_string:

assert_eq!("❤\n!".escape_unicode().to_string(), "\\u{2764}\\u{a}\\u{21}");
1.98.0 · Source

pub fn substr_range(&self, substr: &str) -> Option<Range<usize>>

Returns the range that a substring points to.

Returns None if substr does not point within self.

Unlike str::find, this does not search through the string. Instead, it uses pointer arithmetic to find where in the string substr is derived from.

This is useful for extending str::split and similar methods.

Note that this method may return false positives (typically either Some(0..0) or Some(self.len()..self.len())) if substr is a zero-length str that points at the beginning or end of another, independent, str.

§Examples
use core::range::Range;

let data = "a, b, b, a";
let mut iter = data.split(", ").map(|s| data.substr_range(s).unwrap());

assert_eq!(iter.next(), Some(Range { start: 0, end: 1 }));
assert_eq!(iter.next(), Some(Range { start: 3, end: 4 }));
assert_eq!(iter.next(), Some(Range { start: 6, end: 7 }));
assert_eq!(iter.next(), Some(Range { start: 9, end: 10 }));
Source

pub fn as_str(&self) -> &str

🔬This is a nightly-only experimental API. (str_as_str)

Returns the same string as a string slice &str.

This method is redundant when used directly on &str, but it helps dereferencing other string-like types to string slices, for example references to Box<str> or Arc<str>.

1.0.0 · Source

pub fn replace<P>(&self, from: P, to: &str) -> String
where P: Pattern,

Available on non-no_global_oom_handling only.

Replaces all matches of a pattern with another string.

replace creates a new String, and copies the data from this string slice into it. While doing so, it attempts to find matches of a pattern. If it finds any, it replaces them with the replacement string slice.

§Examples
let s = "this is old";

assert_eq!("this is new", s.replace("old", "new"));
assert_eq!("than an old", s.replace("is", "an"));

When the pattern doesn’t match, it returns this string slice as String:

let s = "this is old";
assert_eq!(s, s.replace("cookie monster", "little lamb"));
1.16.0 · Source

pub fn replacen<P>(&self, pat: P, to: &str, count: usize) -> String
where P: Pattern,

Available on non-no_global_oom_handling only.

Replaces first N matches of a pattern with another string.

replacen creates a new String, and copies the data from this string slice into it. While doing so, it attempts to find matches of a pattern. If it finds any, it replaces them with the replacement string slice at most count times.

§Examples
let s = "foo foo 123 foo";
assert_eq!("new new 123 foo", s.replacen("foo", "new", 2));
assert_eq!("faa fao 123 foo", s.replacen('o', "a", 3));
assert_eq!("foo foo new23 foo", s.replacen(char::is_numeric, "new", 1));

When the pattern doesn’t match, it returns this string slice as String:

let s = "this is old";
assert_eq!(s, s.replacen("cookie monster", "little lamb", 10));
1.2.0 · Source

pub fn to_lowercase(&self) -> String

Available on non-no_global_oom_handling only.

Returns the lowercase equivalent of this string slice, as a new String.

‘Lowercase’ is defined according to the terms of Chapter 3 (Conformance) of the Unicode standard.

Since some characters can expand into multiple characters when changing the case, this function returns a String instead of modifying the parameter in-place.

Unlike char::to_lowercase(), this method fully handles the context-dependent casing of Greek sigma. However, like that method, it does not handle locale-specific casing, like Turkish and Azeri I/ı/İ/i. See its documentation for more information.

§Examples

Basic usage:

let s = "HELLO WORLD";

assert_eq!("hello world", s.to_lowercase());

Tricky examples, with sigma:

let sigma = "Σ";

assert_eq!("σ", sigma.to_lowercase());

// but at the end of a word, it's ς, not σ:
let odysseus = "ὈΔΥΣΣΕΎΣ";

assert_eq!("ὀδυσσεύς", odysseus.to_lowercase());

let odysseus_king_of_ithaca = "Ο ΟΔΥΣΣΈΑΣ ΒΑΣΙΛΙΆΣ ΤΗΣ ΙΘΆΚΗΣ";

assert_eq!("ο οδυσσέας βασιλιάς της ιθάκης", odysseus_king_of_ithaca.to_lowercase());

Languages without case are not changed:

let new_year = "农历新年";

assert_eq!(new_year, new_year.to_lowercase());
Examples found in repository?
examples/testbed/ui.rs (line 102)
100    fn from_str(s: &str) -> Result<Self, Self::Err> {
101        let mut isit = Self::default();
102        while s.to_lowercase() != format!("{isit:?}").to_lowercase() {
103            isit = isit.next();
104            if isit == Self::default() {
105                return Err(format!("Invalid Scene name: {s}"));
106            }
107        }
108        Ok(isit)
109    }
More examples
Hide additional examples
examples/testbed/2d.rs (line 71)
69    fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
70        let mut isit = Self::default();
71        while s.to_lowercase() != format!("{isit:?}").to_lowercase() {
72            isit = isit.next();
73            if isit == Self::default() {
74                return Err(format!("Invalid Scene name: {s}"));
75            }
76        }
77        Ok(isit)
78    }
examples/testbed/3d.rs (line 82)
80    fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
81        let mut isit = Self::default();
82        while s.to_lowercase() != format!("{isit:?}").to_lowercase() {
83            isit = isit.next();
84            if isit == Self::default() {
85                return Err(format!("Invalid Scene name: {s}"));
86            }
87        }
88        Ok(isit)
89    }
Source

pub fn word_to_titlecase(&self) -> String

🔬This is a nightly-only experimental API. (titlecase)
Available on non-no_global_oom_handling only.

Returns the titlecase equivalent of this string slice, which is assumed to represent a single word, as a new String.

Essentially, this consists of uppercasing the first cased letter (with char::to_titlecase()), and lowercasing everything that follows.

‘Titlecase’ is defined according to the terms of Chapter 3 (Conformance) of the Unicode standard.

Since some characters can expand into multiple characters when changing the case, this function returns a String instead of modifying the parameter in-place.

Unlike char::to_lowercase(), this method fully handles the context-dependent casing of Greek sigma. However, like that method, it does not handle locale-specific casing, like Turkish and Azeri I/ı/İ/i. See its documentation for more information.

This method does not perform any kind of word segmentation.

§Examples

Basic usage:

#![feature(titlecase)]
let s = "HELLO WORLD";

assert_eq!("Hello world", s.word_to_titlecase());

The first cased letter is uppercased:

#![feature(titlecase)]
let the_night_before_christmas = "'twas";

assert_eq!("'Twas", the_night_before_christmas.word_to_titlecase());

Languages without case are not changed:

#![feature(titlecase)]
let new_year = "农历新年";

assert_eq!(new_year, new_year.word_to_titlecase());

Georgian uppercase (“Mtavruli”) letters are not used in titlecase:

#![feature(titlecase)]
let georgian = "ერთობაშია";

assert_eq!(georgian, georgian.word_to_titlecase());

No word segmentation is performed, so only the first cased letter in the whole string gets uppercased:

#![feature(titlecase)]
let blazingly_fast = "ferris and I";

assert_eq!("Ferris and i", blazingly_fast.word_to_titlecase());

Tricky examples, with sigma:

#![feature(titlecase)]
let odysseus = "ὈΔΥΣΣΕΎΣ";

assert_eq!("Ὀδυσσεύς", odysseus.word_to_titlecase());

let odysseus_king_of_ithaca = "Ο ΟΔΥΣΣΈΑΣ ΒΑΣΙΛΙΆΣ ΤΗΣ ΙΘΆΚΗΣ";

assert_eq!("Ο οδυσσέας βασιλιάς της ιθάκης", odysseus_king_of_ithaca.word_to_titlecase());
1.2.0 · Source

pub fn to_uppercase(&self) -> String

Available on non-no_global_oom_handling only.

Returns the uppercase equivalent of this string slice, as a new String.

‘Uppercase’ is defined according to the terms of Chapter 3 (Conformance) of the Unicode standard.

Since some characters can expand into multiple characters when changing the case, this function returns a String instead of modifying the parameter in-place.

Like char::to_uppercase() this method does not handle language-specific casing, like Turkish and Azeri I/ı/İ/i. See that method’s documentation for more information.

§Examples

Basic usage:

let s = "hello world";

assert_eq!("HELLO WORLD", s.to_uppercase());

Scripts without case are not changed:

let new_year = "农历新年";

assert_eq!(new_year, new_year.to_uppercase());

One character can become multiple:

let s = "tschüß";

assert_eq!("TSCHÜSS", s.to_uppercase());
Source

pub fn to_casefold_unnormalized(&self) -> String

🔬This is a nightly-only experimental API. (casefold)
Available on non-no_global_oom_handling only.

Returns the case-folded equivalent of this string slice, as a new String.

Case folding is a transformation, mostly matching lowercase, that is meant to be used for case-insensitive string comparisons. Case-folded strings should not usually be exposed directly to users.

For the precise specification of case folding, see Chapter 3 (Conformance) of the Unicode standard.

Since some characters can expand into multiple characters when case folding, this function returns a String instead of modifying the parameter in-place.

No normalization (e.g. NFC) is performed, so visually and semantically identical strings might still casefold differently. For example, "Å" (U+00C5 LATIN CAPITAL LETTER A WITH RING ABOVE) is considered distinct from "Å" (A followed by U+030A COMBINING RING ABOVE), even though Unicode considers them canonically equivalent.

Like char::to_casefold_unnormalized() this method does not handle language-specific casing, like Turkish and Azeri I/ı/İ/i. See that method’s documentation for more information.

§Examples

Basic usage:

#![feature(casefold)]
let s0 = "HELLO";
let s1 = "Hello";

assert_eq!(s0.to_casefold_unnormalized(), s1.to_casefold_unnormalized());
assert_eq!(s0.to_casefold_unnormalized(), "hello")

Scripts without case are not changed:

#![feature(casefold)]
let new_year = "农历新年";

assert_eq!(new_year, new_year.to_casefold_unnormalized());

One character can become multiple:

#![feature(casefold)]
let s0 = "TSCHÜẞ";
let s1 = "TSCHÜSS";
let s2 = "tschüß";

assert_eq!(s0.to_casefold_unnormalized(), s1.to_casefold_unnormalized());
assert_eq!(s0.to_casefold_unnormalized(), s2.to_casefold_unnormalized());
assert_eq!(s0.to_casefold_unnormalized(), "tschüss");

No NFC normalization is performed:

#![feature(casefold)]
// These two strings are visually and semantically identical...
let comp = "Å";
let decomp = "Å";

// ... but not codepoint-for-codepoint equal.
assert_eq!(comp, "\u{C5}");
assert_eq!(decomp, "A\u{030A}");

// Their case-foldings are likewise unequal:
assert_eq!(comp.to_casefold_unnormalized(), "\u{E5}");
assert_eq!(decomp.to_casefold_unnormalized(), "a\u{030A}");
1.16.0 · Source

pub fn repeat(&self, n: usize) -> String

Available on non-no_global_oom_handling only.

Creates a new String by repeating a string n times.

§Panics

This function will panic if the capacity would overflow.

§Examples

Basic usage:

assert_eq!("abc".repeat(4), String::from("abcabcabcabc"));

A panic upon overflow:

// this will panic at runtime
let huge = "0123456789abcdef".repeat(usize::MAX);
Examples found in repository?
examples/stress_tests/many_glyphs.rs (line 68)
64fn setup(mut commands: Commands, args: Res<Args>) {
65    warn!(include_str!("warning_string.txt"));
66
67    commands.spawn(Camera2d);
68    let text_string = "0123456789".repeat(10_000);
69    let text_font = TextFont {
70        font_size: FontSize::Px(4.),
71        ..Default::default()
72    };
73    let text_block = TextLayout {
74        justify: Justify::Left,
75        linebreak: LineBreak::AnyCharacter,
76    };
77
78    if !args.no_ui {
79        commands
80            .spawn(Node {
81                width: percent(100),
82                align_items: AlignItems::Center,
83                justify_content: JustifyContent::Center,
84                ..default()
85            })
86            .with_children(|commands| {
87                commands
88                    .spawn(Node {
89                        width: px(1000),
90                        ..Default::default()
91                    })
92                    .with_child((Text(text_string.clone()), text_font.clone(), text_block));
93            });
94    }
95
96    if !args.no_text2d {
97        commands.spawn((
98            Text2d::new(text_string),
99            text_font.clone(),
100            TextColor(RED.into()),
101            bevy::sprite::Anchor::CENTER,
102            TextBounds::new_horizontal(1000.),
103            text_block,
104        ));
105    }
106}
More examples
Hide additional examples
examples/stress_tests/text_pipeline.rs (line 42)
34fn spawn(mut commands: Commands, asset_server: Res<AssetServer>) {
35    warn!(include_str!("warning_string.txt"));
36
37    commands.spawn(Camera2d);
38
39    let make_spans = |i| {
40        [
41            (
42                TextSpan("text".repeat(i)),
43                TextFont {
44                    font: asset_server.load("fonts/FiraMono-Medium.ttf").into(),
45                    font_size: FontSize::Px((4 + i % 10) as f32),
46                    ..Default::default()
47                },
48                TextColor(BLUE.into()),
49            ),
50            (
51                TextSpan("pipeline".repeat(i)),
52                TextFont {
53                    font: asset_server.load("fonts/FiraSans-Bold.ttf").into(),
54                    font_size: FontSize::Px((4 + i % 11) as f32),
55                    ..default()
56                },
57                TextColor(YELLOW.into()),
58            ),
59        ]
60    };
61
62    let spans = (1..50).flat_map(|i| make_spans(i).into_iter());
63
64    commands
65        .spawn((
66            Text2d::default(),
67            TextLayout {
68                justify: Justify::Center,
69                linebreak: LineBreak::AnyCharacter,
70            },
71            TextBounds::default(),
72        ))
73        .with_children(|p| {
74            for span in spans {
75                p.spawn(span);
76            }
77        });
78}
1.23.0 · Source

pub fn to_ascii_uppercase(&self) -> String

Available on non-no_global_oom_handling only.

Returns a copy of this string where each character is mapped to its ASCII upper case equivalent.

ASCII letters ‘a’ to ‘z’ are mapped to ‘A’ to ‘Z’, but non-ASCII letters are unchanged.

To uppercase the value in-place, use make_ascii_uppercase.

To uppercase ASCII characters in addition to non-ASCII characters, use to_uppercase.

§Examples
let s = "Grüße, Jürgen ❤";

assert_eq!("GRüßE, JüRGEN ❤", s.to_ascii_uppercase());
1.23.0 · Source

pub fn to_ascii_lowercase(&self) -> String

Available on non-no_global_oom_handling only.

Returns a copy of this string where each character is mapped to its ASCII lower case equivalent.

ASCII letters ‘A’ to ‘Z’ are mapped to ‘a’ to ‘z’, but non-ASCII letters are unchanged.

To lowercase the value in-place, use make_ascii_lowercase.

To lowercase ASCII characters in addition to non-ASCII characters, use to_lowercase.

§Examples
let s = "Grüße, Jürgen ❤";

assert_eq!("grüße, jürgen ❤", s.to_ascii_lowercase());

Trait Implementations§

Source§

impl<'i> Accumulate<&'i str> for String

Available on crate feature alloc only.
Source§

fn initial(capacity: Option<usize>) -> String

Create a new Extend of the correct type
Source§

fn accumulate(&mut self, acc: &'i str)

Accumulate the input into an accumulator
Source§

impl<'i> Accumulate<Cow<'i, str>> for String

Available on crate feature alloc only.
Source§

fn initial(capacity: Option<usize>) -> String

Create a new Extend of the correct type
Source§

fn accumulate(&mut self, acc: Cow<'i, str>)

Accumulate the input into an accumulator
Source§

impl Accumulate<String> for String

Available on crate feature alloc only.
Source§

fn initial(capacity: Option<usize>) -> String

Create a new Extend of the correct type
Source§

fn accumulate(&mut self, acc: String)

Accumulate the input into an accumulator
Source§

impl Accumulate<char> for String

Available on crate feature alloc only.
Source§

fn initial(capacity: Option<usize>) -> String

Create a new Extend of the correct type
Source§

fn accumulate(&mut self, acc: char)

Accumulate the input into an accumulator
1.0.0 · Source§

impl Add<&str> for String

Available on non-no_global_oom_handling only.

Implements the + operator for concatenating two strings.

This consumes the String on the left-hand side and re-uses its buffer (growing it if necessary). This is done to avoid allocating a new String and copying the entire contents on every operation, which would lead to O(n^2) running time when building an n-byte string by repeated concatenation.

The string on the right-hand side is only borrowed; its contents are copied into the returned String.

§Examples

Concatenating two Strings takes the first by value and borrows the second:

let a = String::from("hello");
let b = String::from(" world");
let c = a + &b;
// `a` is moved and can no longer be used here.

If you want to keep using the first String, you can clone it and append to the clone instead:

let a = String::from("hello");
let b = String::from(" world");
let c = a.clone() + &b;
// `a` is still valid here.

Concatenating &str slices can be done by converting the first to a String:

let a = "hello";
let b = " world";
let c = a.to_string() + b;
Source§

type Output = String

The resulting type after applying the + operator.
Source§

fn add(self, other: &str) -> String

Performs the + operation. Read more
1.12.0 · Source§

impl AddAssign<&str> for String

Available on non-no_global_oom_handling only.

Implements the += operator for appending to a String.

This has the same behavior as the push_str method.

Source§

fn add_assign(&mut self, other: &str)

Performs the += operation. Read more
Source§

impl Arg for &String

Available on crate feature alloc only.
Source§

fn as_str(&self) -> Result<&str, Errno>

Returns a view of this string as a string slice.
Source§

fn to_string_lossy(&self) -> Cow<'_, str>

Returns a potentially-lossy rendering of this string as a Cow<'_, str>.
Source§

fn as_cow_c_str(&self) -> Result<Cow<'_, CStr>, Errno>

Returns a view of this string as a maybe-owned CStr.
Source§

fn into_c_str<'b>(self) -> Result<Cow<'b, CStr>, Errno>
where &String: 'b,

Consumes self and returns a view of this string as a maybe-owned CStr.
Source§

fn into_with_c_str<T, F>(self, f: F) -> Result<T, Errno>
where &String: Sized, F: FnOnce(&CStr) -> Result<T, Errno>,

Runs a closure with self passed in as a &CStr.
Source§

impl Arg for String

Available on crate feature alloc only.
Source§

fn as_str(&self) -> Result<&str, Errno>

Returns a view of this string as a string slice.
Source§

fn to_string_lossy(&self) -> Cow<'_, str>

Returns a potentially-lossy rendering of this string as a Cow<'_, str>.
Source§

fn as_cow_c_str(&self) -> Result<Cow<'_, CStr>, Errno>

Returns a view of this string as a maybe-owned CStr.
Source§

fn into_c_str<'b>(self) -> Result<Cow<'b, CStr>, Errno>
where String: 'b,

Consumes self and returns a view of this string as a maybe-owned CStr.
Source§

fn into_with_c_str<T, F>(self, f: F) -> Result<T, Errno>
where String: Sized, F: FnOnce(&CStr) -> Result<T, Errno>,

Runs a closure with self passed in as a &CStr.
Source§

impl Arg for &String

Available on crate feature alloc only.
Source§

fn as_str(&self) -> Result<&str, Errno>

Returns a view of this string as a string slice.
Source§

fn to_string_lossy(&self) -> Cow<'_, str>

Returns a potentially-lossy rendering of this string as a Cow<'_, str>.
Source§

fn as_cow_c_str(&self) -> Result<Cow<'_, CStr>, Errno>

Returns a view of this string as a maybe-owned CStr.
Source§

fn into_c_str<'b>(self) -> Result<Cow<'b, CStr>, Errno>
where &String: 'b,

Consumes self and returns a view of this string as a maybe-owned CStr.
Source§

fn into_with_c_str<T, F>(self, f: F) -> Result<T, Errno>
where &String: Sized, F: FnOnce(&CStr) -> Result<T, Errno>,

Runs a closure with self passed in as a &CStr.
Source§

impl Arg for String

Available on crate feature alloc only.
Source§

fn as_str(&self) -> Result<&str, Errno>

Returns a view of this string as a string slice.
Source§

fn to_string_lossy(&self) -> Cow<'_, str>

Returns a potentially-lossy rendering of this string as a Cow<'_, str>.
Source§

fn as_cow_c_str(&self) -> Result<Cow<'_, CStr>, Errno>

Returns a view of this string as a maybe-owned CStr.
Source§

fn into_c_str<'b>(self) -> Result<Cow<'b, CStr>, Errno>
where String: 'b,

Consumes self and returns a view of this string as a maybe-owned CStr.
Source§

fn into_with_c_str<T, F>(self, f: F) -> Result<T, Errno>
where String: Sized, F: FnOnce(&CStr) -> Result<T, Errno>,

Runs a closure with self passed in as a &CStr.
Source§

impl AsHeaderName for String

Source§

impl AsHeaderName for &String

1.43.0 · Source§

impl AsMut<str> for String

Source§

fn as_mut(&mut self) -> &mut str

Converts this type into a mutable reference of the (usually inferred) input type.
1.0.0 · Source§

impl AsRef<OsStr> for String

Source§

fn as_ref(&self) -> &OsStr

Converts this type into a shared reference of the (usually inferred) input type.
1.0.0 · Source§

impl AsRef<Path> for String

Source§

fn as_ref(&self) -> &Path

Converts this type into a shared reference of the (usually inferred) input type.
1.0.0 · Source§

impl AsRef<[u8]> for String

Source§

fn as_ref(&self) -> &[u8]

Converts this type into a shared reference of the (usually inferred) input type.
1.0.0 · Source§

impl AsRef<str> for String

Source§

fn as_ref(&self) -> &str

Converts this type into a shared reference of the (usually inferred) input type.
Source§

impl AsSendBody for String

Source§

impl AsSendBody for &String

Source§

impl Basic for String

Source§

const SIGNATURE_CHAR: char = 's'

The type signature, as a character.
Source§

const SIGNATURE_STR: &'static str = "s"

The type signature, as a string.
Source§

fn alignment(format: Format) -> usize

The required padding alignment for the given format. Read more
Source§

impl Body for String

Source§

type Data = Bytes

Values yielded by the Body.
Source§

type Error = Infallible

The error type this Body might generate.
Source§

fn poll_frame( self: Pin<&mut String>, _cx: &mut Context<'_>, ) -> Poll<Option<Result<Frame<<String as Body>::Data>, <String as Body>::Error>>>

Attempt to pull out the next frame of this stream. Read more
Source§

fn is_end_stream(&self) -> bool

A hint that may return true when the end of stream has been reached. Read more
Source§

fn size_hint(&self) -> SizeHint

A hint that returns the bounds on the remaining length of the stream. Read more
1.0.0 · Source§

impl Borrow<str> for String

Source§

fn borrow(&self) -> &str

Immutably borrows from an owned value. Read more
1.36.0 · Source§

impl BorrowMut<str> for String

Source§

fn borrow_mut(&mut self) -> &mut str

Mutably borrows from an owned value. Read more
Source§

impl Clear for String

Source§

fn clear(&mut self)

Clear all data in self, retaining the allocated capacithy.
1.0.0 · Source§

impl Clone for String

Available on non-no_global_oom_handling only.
Source§

fn clone_from(&mut self, source: &String)

Clones the contents of source into self.

This method is preferred over simply assigning source.clone() to self, as it avoids reallocation if possible.

Source§

fn clone(&self) -> String

Returns a duplicate of the value. Read more
1.0.0 · Source§

impl Debug for String

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
1.0.0 (const: unstable) · Source§

impl Default for String

Source§

fn default() -> String

Creates an empty String.

1.0.0 · Source§

impl Deref for String

Source§

type Target = str

The resulting type after dereferencing.
Source§

fn deref(&self) -> &str

Dereferences the value.
1.3.0 · Source§

impl DerefMut for String

Source§

fn deref_mut(&mut self) -> &mut str

Mutably dereferences the value.
Source§

impl DerefPure for String

Source§

impl<'de> Deserialize<'de> for String

Available on crate features alloc or std only.
Source§

fn deserialize<D>( deserializer: D, ) -> Result<String, <D as Deserializer<'de>>::Error>
where D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer. Read more
1.0.0 · Source§

impl Display for String

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
Source§

impl EncodeAsVarULE<str> for String

Available on crate feature alloc only.
Source§

fn encode_var_ule_as_slices<R>(&self, cb: impl FnOnce(&[&[u8]]) -> R) -> R

Calls cb with a piecewise list of byte slices that when concatenated produce the memory pattern of the corresponding instance of T. Read more
Source§

fn encode_var_ule_len(&self) -> usize

Return the length, in bytes, of the corresponding VarULE type
Source§

fn encode_var_ule_write(&self, dst: &mut [u8])

Write the corresponding VarULE type to the dst buffer. dst should be the size of Self::encode_var_ule_len()
Source§

impl EncodeAsVarULE<str> for &String

Available on crate feature alloc only.
Source§

fn encode_var_ule_as_slices<R>(&self, cb: impl FnOnce(&[&[u8]]) -> R) -> R

Calls cb with a piecewise list of byte slices that when concatenated produce the memory pattern of the corresponding instance of T. Read more
Source§

fn encode_var_ule_len(&self) -> usize

Return the length, in bytes, of the corresponding VarULE type
Source§

fn encode_var_ule_write(&self, dst: &mut [u8])

Write the corresponding VarULE type to the dst buffer. dst should be the size of Self::encode_var_ule_len()
1.0.0 · Source§

impl Eq for String

Source§

impl<'a> Extend<&'a AsciiChar> for String

Available on non-no_global_oom_handling only.
Source§

fn extend<I>(&mut self, iter: I)
where I: IntoIterator<Item = &'a AsciiChar>,

Extends a collection with the contents of an iterator. Read more
Source§

fn extend_one(&mut self, c: &'a AsciiChar)

🔬This is a nightly-only experimental API. (extend_one)
Extends a collection with exactly one element.
Source§

fn extend_reserve(&mut self, additional: usize)

🔬This is a nightly-only experimental API. (extend_one)
Reserves capacity in a collection for the given number of additional elements. Read more
1.2.0 · Source§

impl<'a> Extend<&'a char> for String

Available on non-no_global_oom_handling only.
Source§

fn extend<I>(&mut self, iter: I)
where I: IntoIterator<Item = &'a char>,

Extends a collection with the contents of an iterator. Read more
Source§

fn extend_one(&mut self, _: &'a char)

🔬This is a nightly-only experimental API. (extend_one)
Extends a collection with exactly one element.
Source§

fn extend_reserve(&mut self, additional: usize)

🔬This is a nightly-only experimental API. (extend_one)
Reserves capacity in a collection for the given number of additional elements. Read more
1.0.0 · Source§

impl<'a> Extend<&'a str> for String

Available on non-no_global_oom_handling only.
Source§

fn extend<I>(&mut self, iter: I)
where I: IntoIterator<Item = &'a str>,

Extends a collection with the contents of an iterator. Read more
Source§

fn extend_one(&mut self, s: &'a str)

🔬This is a nightly-only experimental API. (extend_one)
Extends a collection with exactly one element.
Source§

fn extend_reserve(&mut self, additional: usize)

🔬This is a nightly-only experimental API. (extend_one)
Reserves capacity in a collection for the given number of additional elements. Read more
Source§

impl Extend<AsciiChar> for String

Available on non-no_global_oom_handling only.
Source§

fn extend<I>(&mut self, iter: I)
where I: IntoIterator<Item = AsciiChar>,

Extends a collection with the contents of an iterator. Read more
Source§

fn extend_one(&mut self, c: AsciiChar)

🔬This is a nightly-only experimental API. (extend_one)
Extends a collection with exactly one element.
Source§

fn extend_reserve(&mut self, additional: usize)

🔬This is a nightly-only experimental API. (extend_one)
Reserves capacity in a collection for the given number of additional elements. Read more
1.45.0 · Source§

impl<A> Extend<Box<str, A>> for String
where A: Allocator,

Available on non-no_global_oom_handling only.
Source§

fn extend<I>(&mut self, iter: I)
where I: IntoIterator<Item = Box<str, A>>,

Extends a collection with the contents of an iterator. Read more
Source§

fn extend_one(&mut self, item: A)

🔬This is a nightly-only experimental API. (extend_one)
Extends a collection with exactly one element.
Source§

fn extend_reserve(&mut self, additional: usize)

🔬This is a nightly-only experimental API. (extend_one)
Reserves capacity in a collection for the given number of additional elements. Read more
Source§

impl<A> Extend<Box<str, A>> for String
where A: Allocator,

Available on crate feature alloc only.
Source§

fn extend<I>(&mut self, iter: I)
where I: IntoIterator<Item = Box<str, A>>,

Extends a collection with the contents of an iterator. Read more
Source§

fn extend_one(&mut self, item: A)

🔬This is a nightly-only experimental API. (extend_one)
Extends a collection with exactly one element.
Source§

fn extend_reserve(&mut self, additional: usize)

🔬This is a nightly-only experimental API. (extend_one)
Reserves capacity in a collection for the given number of additional elements. Read more
1.19.0 · Source§

impl<'a> Extend<Cow<'a, str>> for String

Available on non-no_global_oom_handling only.
Source§

fn extend<I>(&mut self, iter: I)
where I: IntoIterator<Item = Cow<'a, str>>,

Extends a collection with the contents of an iterator. Read more
Source§

fn extend_one(&mut self, s: Cow<'a, str>)

🔬This is a nightly-only experimental API. (extend_one)
Extends a collection with exactly one element.
Source§

fn extend_reserve(&mut self, additional: usize)

🔬This is a nightly-only experimental API. (extend_one)
Reserves capacity in a collection for the given number of additional elements. Read more
1.4.0 · Source§

impl Extend<String> for String

Available on non-no_global_oom_handling only.
Source§

fn extend<I>(&mut self, iter: I)
where I: IntoIterator<Item = String>,

Extends a collection with the contents of an iterator. Read more
Source§

fn extend_one(&mut self, s: String)

🔬This is a nightly-only experimental API. (extend_one)
Extends a collection with exactly one element.
Source§

fn extend_reserve(&mut self, additional: usize)

🔬This is a nightly-only experimental API. (extend_one)
Reserves capacity in a collection for the given number of additional elements. Read more
1.0.0 · Source§

impl Extend<char> for String

Available on non-no_global_oom_handling only.
Source§

fn extend<I>(&mut self, iter: I)
where I: IntoIterator<Item = char>,

Extends a collection with the contents of an iterator. Read more
Source§

fn extend_one(&mut self, c: char)

🔬This is a nightly-only experimental API. (extend_one)
Extends a collection with exactly one element.
Source§

fn extend_reserve(&mut self, additional: usize)

🔬This is a nightly-only experimental API. (extend_one)
Reserves capacity in a collection for the given number of additional elements. Read more
Source§

impl FmtConst for String

Source§

fn fmt_const(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Print a const expression representing this value.
1.28.0 · Source§

impl<'a> From<&'a String> for Cow<'a, str>

Available on non-no_global_oom_handling only.
Source§

fn from(s: &'a String) -> Cow<'a, str>

Converts a String reference into a Borrowed variant. No heap allocation is performed, and the string is not copied.

§Example
let s = "eggplant".to_string();
assert_eq!(Cow::from(&s), Cow::Borrowed("eggplant"));
Source§

impl<'a> From<&'a String> for AssetPath<'a>

Source§

fn from(asset_path: &'a String) -> AssetPath<'a>

Converts to this type from the input type.
Source§

impl From<&Name> for String

Source§

fn from(val: &Name) -> String

Converts to this type from the input type.
1.35.0 · Source§

impl From<&String> for String

Available on non-no_global_oom_handling only.
Source§

fn from(s: &String) -> String

Converts a &String into a String.

This clones s and returns the clone.

1.44.0 · Source§

impl From<&mut str> for String

Available on non-no_global_oom_handling only.
Source§

fn from(s: &mut str) -> String

Converts a &mut str into a String.

The result is allocated on the heap.

1.0.0 · Source§

impl From<&str> for String

Available on non-no_global_oom_handling only.
Source§

fn from(s: &str) -> String

Converts a &str into a String.

The result is allocated on the heap.

1.18.0 · Source§

impl From<Box<str>> for String

Source§

fn from(s: Box<str>) -> String

Converts the given boxed str slice to a String. It is notable that the str slice is owned.

§Examples
let s1: String = String::from("hello world");
let s2: Box<str> = s1.into_boxed_str();
let s3: String = String::from(s2);

assert_eq!("hello world", s3)
1.14.0 · Source§

impl<'a> From<Cow<'a, str>> for String

Available on non-no_global_oom_handling only.
Source§

fn from(s: Cow<'a, str>) -> String

Converts a clone-on-write string to an owned instance of String.

This extracts the owned string, clones the string if it is not already owned.

§Example
// If the string is not owned...
let cow: Cow<'_, str> = Cow::Borrowed("eggplant");
// It will allocate on the heap and copy the string.
let owned: String = String::from(cow);
assert_eq!(&owned[..], "eggplant");
Source§

impl From<DiagnosticPath> for String

Source§

fn from(path: DiagnosticPath) -> String

Converts to this type from the input type.
Source§

impl From<Guid<'_>> for String

Source§

fn from(guid: Guid<'_>) -> String

Converts to this type from the input type.
Source§

impl From<Name> for String

Source§

fn from(val: Name) -> String

Converts to this type from the input type.
Source§

impl From<ScriptLangTag<'_>> for String

Available on crate feature std only.
Source§

fn from(value: ScriptLangTag<'_>) -> String

Converts to this type from the input type.
Source§

impl From<SmolStr> for String

Source§

fn from(text: SmolStr) -> String

Converts to this type from the input type.
Source§

impl<'a> From<Str<'a>> for String

Source§

fn from(value: Str<'a>) -> String

Converts to this type from the input type.
1.0.0 · Source§

impl<'a> From<String> for Box<dyn Error + Sync + Send + 'a>

Available on non-no_global_oom_handling only.
Source§

fn from(err: String) -> Box<dyn Error + Sync + Send + 'a>

Converts a String into a box of dyn Error + Send + Sync.

§Examples
use std::error::Error;

let a_string_error = "a string error".to_string();
let a_boxed_error = Box::<dyn Error + Send + Sync>::from(a_string_error);
assert!(
    size_of::<Box<dyn Error + Send + Sync>>() == size_of_val(&a_boxed_error))
1.6.0 · Source§

impl<'a> From<String> for Box<dyn Error + 'a>

Available on non-no_global_oom_handling only.
Source§

fn from(str_err: String) -> Box<dyn Error + 'a>

Converts a String into a box of dyn Error.

§Examples
use std::error::Error;

let a_string_error = "a string error".to_string();
let a_boxed_error = Box::<dyn Error>::from(a_string_error);
assert!(size_of::<Box<dyn Error>>() == size_of_val(&a_boxed_error))
1.20.0 · Source§

impl From<String> for Box<str>

Available on non-no_global_oom_handling only.
Source§

fn from(s: String) -> Box<str>

Converts the given String to a boxed str slice that is owned.

§Examples
let s1: String = String::from("hello world");
let s2: Box<str> = Box::from(s1);
let s3: String = String::from(s2);

assert_eq!("hello world", s3)
1.0.0 · Source§

impl<'a> From<String> for Cow<'a, str>

Available on non-no_global_oom_handling only.
Source§

fn from(s: String) -> Cow<'a, str>

Converts a String into an Owned variant. No heap allocation is performed, and the string is not copied.

§Example
let s = "eggplant".to_string();
let s2 = "eggplant".to_string();
assert_eq!(Cow::from(s), Cow::<'static, str>::Owned(s2));
1.14.0 · Source§

impl From<String> for Vec<u8>

Source§

fn from(string: String) -> Vec<u8>

Converts the given String to a vector Vec that holds values of type u8.

§Examples
let s1 = String::from("hello world");
let v1 = Vec::from(s1);

for b in v1 {
    println!("{b}");
}
1.21.0 · Source§

impl From<String> for Arc<str>

Available on non-no_global_oom_handling only.
Source§

fn from(v: String) -> Arc<str>

Allocates a reference-counted str and copies v into it.

§Example
let unique: String = "eggplant".to_owned();
let shared: Arc<str> = Arc::from(unique);
assert_eq!("eggplant", &shared[..]);
Source§

impl From<String> for HashedStr

Source§

fn from(value: String) -> HashedStr

Converts to this type from the input type.
Source§

impl From<String> for Name

Source§

fn from(name: String) -> Name

Converts to this type from the input type.
Source§

impl From<String> for DebugName

Source§

fn from(value: String) -> DebugName

Converts to this type from the input type.
Source§

impl From<String> for AssetSourceId<'static>

Source§

fn from(value: String) -> AssetSourceId<'static>

Converts to this type from the input type.
Source§

impl From<String> for AssetPath<'static>

Source§

fn from(asset_path: String) -> AssetPath<'static>

Converts to this type from the input type.
Source§

impl From<String> for ShaderDefVal

Source§

fn from(key: String) -> ShaderDefVal

Converts to this type from the input type.
Source§

impl From<String> for TextSpan

Source§

fn from(value: String) -> TextSpan

Converts to this type from the input type.
Source§

impl From<String> for Text

Source§

fn from(value: String) -> Text

Converts to this type from the input type.
Source§

impl From<String> for Text2d

Source§

fn from(value: String) -> Text2d

Converts to this type from the input type.
Source§

impl From<SvgPen> for String

Source§

fn from(value: SvgPen) -> String

Converts to this type from the input type.
Source§

impl From<Text> for String

Source§

fn from(val: Text) -> String

Converts to this type from the input type.
Source§

impl From<Uuid> for String

Available on crate feature std only.
Source§

fn from(uuid: Uuid) -> String

Converts to this type from the input type.
1.46.0 · Source§

impl From<char> for String

Available on non-no_global_oom_handling only.
Source§

fn from(c: char) -> String

Allocates an owned String from a single character.

§Example
let c: char = 'a';
let s: String = String::from(c);
assert_eq!("a", &s[..]);
Source§

impl FromArg for String

Source§

type This<'from_arg> = String

The type to convert into. Read more
Source§

fn from_arg(arg: Arg<'_>) -> Result<<String as FromArg>::This<'_>, ArgError>

Creates an item from an argument. Read more
Source§

impl<'a> FromIterator<&'a AsciiChar> for String

Available on non-no_global_oom_handling only.
Source§

fn from_iter<T>(iter: T) -> String
where T: IntoIterator<Item = &'a AsciiChar>,

Creates a value from an iterator. Read more
1.17.0 · Source§

impl<'a> FromIterator<&'a char> for String

Available on non-no_global_oom_handling only.
Source§

fn from_iter<I>(iter: I) -> String
where I: IntoIterator<Item = &'a char>,

Creates a value from an iterator. Read more
1.0.0 · Source§

impl<'a> FromIterator<&'a str> for String

Available on non-no_global_oom_handling only.
Source§

fn from_iter<I>(iter: I) -> String
where I: IntoIterator<Item = &'a str>,

Creates a value from an iterator. Read more
Source§

impl FromIterator<AsciiChar> for String

Available on non-no_global_oom_handling only.
Source§

fn from_iter<T>(iter: T) -> String
where T: IntoIterator<Item = AsciiChar>,

Creates a value from an iterator. Read more
1.45.0 · Source§

impl<A> FromIterator<Box<str, A>> for String
where A: Allocator,

Available on non-no_global_oom_handling only.
Source§

fn from_iter<I>(iter: I) -> String
where I: IntoIterator<Item = Box<str, A>>,

Creates a value from an iterator. Read more
1.19.0 · Source§

impl<'a> FromIterator<Cow<'a, str>> for String

Available on non-no_global_oom_handling only.
Source§

fn from_iter<I>(iter: I) -> String
where I: IntoIterator<Item = Cow<'a, str>>,

Creates a value from an iterator. Read more
1.80.0 · Source§

impl FromIterator<String> for Box<str>

Available on non-no_global_oom_handling only.
Source§

fn from_iter<T>(iter: T) -> Box<str>
where T: IntoIterator<Item = String>,

Creates a value from an iterator. Read more
1.4.0 · Source§

impl FromIterator<String> for String

Available on non-no_global_oom_handling only.
Source§

fn from_iter<I>(iter: I) -> String
where I: IntoIterator<Item = String>,

Creates a value from an iterator. Read more
1.12.0 · Source§

impl<'a> FromIterator<String> for Cow<'a, str>

Available on non-no_global_oom_handling only.
Source§

fn from_iter<I>(it: I) -> Cow<'a, str>
where I: IntoIterator<Item = String>,

Creates a value from an iterator. Read more
1.0.0 · Source§

impl FromIterator<char> for String

Available on non-no_global_oom_handling only.
Source§

fn from_iter<I>(iter: I) -> String
where I: IntoIterator<Item = char>,

Creates a value from an iterator. Read more
Source§

impl FromReflect for String

Source§

fn from_reflect(reflect: &(dyn PartialReflect + 'static)) -> Option<String>

Constructs a concrete instance of Self from a reflected value.
Source§

fn take_from_reflect( reflect: Box<dyn PartialReflect>, ) -> Result<Self, Box<dyn PartialReflect>>

Attempts to downcast the given value to Self using, constructing the value using from_reflect if that fails. Read more
1.0.0 · Source§

impl FromStr for String

Available on non-no_global_oom_handling only.
Source§

type Err = Infallible

The associated error which can be returned from parsing.
Source§

fn from_str(s: &str) -> Result<String, <String as FromStr>::Err>

Parses a string s to return a value of this type. Read more
Source§

impl GetOwnership for String

Source§

fn ownership() -> Ownership

Returns the ownership of Self.
Source§

impl GetTypeRegistration for String

Source§

fn get_type_registration() -> TypeRegistration

Returns the default TypeRegistration for this type.
Source§

fn register_type_dependencies(_registry: &mut TypeRegistry)

Registers other types needed by this type. Read more
1.0.0 · Source§

impl Hash for String

Source§

fn hash<H>(&self, hasher: &mut H)
where H: Hasher,

Feeds this value into the given Hasher. Read more
1.3.0 · Source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where H: Hasher, Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
Source§

impl IdentFragment for String

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Format this value as an identifier fragment.
Source§

fn span(&self) -> Option<Span>

Span associated with this IdentFragment. Read more
Source§

impl Index for String

Source§

impl Index for String

1.0.0 · Source§

impl<I> Index<I> for String
where I: SliceIndex<str>,

Source§

type Output = <I as SliceIndex<str>>::Output

The returned type after indexing.
Source§

fn index(&self, index: I) -> &<I as SliceIndex<str>>::Output

Performs the indexing (container[index]) operation. Read more
1.0.0 · Source§

impl<I> IndexMut<I> for String
where I: SliceIndex<str>,

Source§

fn index_mut(&mut self, index: I) -> &mut <I as SliceIndex<str>>::Output

Performs the mutable indexing (container[index]) operation. Read more
Source§

impl IntoAttributeValue for String

Source§

fn into_value(self) -> AttributeValue

Convert into an attribute value
Source§

impl IntoClientRequest for &String

Source§

fn into_client_request(self) -> Result<Request<()>, Error>

Convert into a Request that can be used for a client connection.
Source§

impl IntoClientRequest for String

Source§

fn into_client_request(self) -> Result<Request<()>, Error>

Convert into a Request that can be used for a client connection.
Source§

impl<'de, E> IntoDeserializer<'de, E> for String
where E: Error,

Available on crate features alloc or std only.
Source§

type Deserializer = StringDeserializer<E>

The type of the deserializer being converted into.
Source§

fn into_deserializer(self) -> StringDeserializer<E>

Convert this value into a deserializer.
Source§

impl IntoDynNode for String

Source§

fn into_dyn_node(self) -> DynamicNode

Consume this item and produce a DynamicNode
Source§

impl IntoReturn for String

Source§

fn into_return<'into_return>(self) -> Return<'into_return>
where String: 'into_return,

Converts Self into a Return value.
1.0.0 · Source§

impl Ord for String

Source§

fn cmp(&self, other: &String) -> Ordering

This method returns an Ordering between self and other. Read more
1.21.0 (const: unstable) · Source§

fn max(self, other: Self) -> Self
where Self: Sized,

Compares and returns the maximum of two values. Read more
1.21.0 (const: unstable) · Source§

fn min(self, other: Self) -> Self
where Self: Sized,

Compares and returns the minimum of two values. Read more
1.50.0 (const: unstable) · Source§

fn clamp(self, min: Self, max: Self) -> Self
where Self: Sized,

Restrict a value to a certain interval. Read more
1.0.0 · Source§

impl PartialEq for String

Source§

fn eq(&self, other: &String) -> bool

Equality operator ==. Read more
1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Inequality operator !=. Read more
1.0.0 · Source§

impl PartialEq<&str> for String

Source§

fn eq(&self, other: &&str) -> bool

Equality operator ==. Read more
Source§

fn ne(&self, other: &&str) -> bool

Inequality operator !=. Read more
Source§

impl PartialEq<Authority> for String

Source§

fn eq(&self, other: &Authority) -> bool

Equality operator ==. Read more
1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Inequality operator !=. Read more
Source§

impl PartialEq<ByteStr> for String

Source§

fn eq(&self, other: &ByteStr) -> bool

Equality operator ==. Read more
1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Inequality operator !=. Read more
Source§

impl PartialEq<ByteString> for String

Source§

fn eq(&self, other: &ByteString) -> bool

Equality operator ==. Read more
1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Inequality operator !=. Read more
Source§

impl PartialEq<Bytes> for String

Source§

fn eq(&self, other: &Bytes) -> bool

Equality operator ==. Read more
1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Inequality operator !=. Read more
Source§

impl PartialEq<BytesMut> for String

Source§

fn eq(&self, other: &BytesMut) -> bool

Equality operator ==. Read more
1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Inequality operator !=. Read more
1.0.0 · Source§

impl PartialEq<Cow<'_, str>> for String

Source§

fn eq(&self, other: &Cow<'_, str>) -> bool

Equality operator ==. Read more
Source§

fn ne(&self, other: &Cow<'_, str>) -> bool

Inequality operator !=. Read more
Source§

impl PartialEq<HeaderValue> for String

Source§

fn eq(&self, other: &HeaderValue) -> bool

Equality operator ==. Read more
1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Inequality operator !=. Read more
1.91.0 · Source§

impl PartialEq<Path> for String

Source§

fn eq(&self, other: &Path) -> bool

Equality operator ==. Read more
1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Inequality operator !=. Read more
Source§

impl PartialEq<PathAndQuery> for String

Source§

fn eq(&self, other: &PathAndQuery) -> bool

Equality operator ==. Read more
1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Inequality operator !=. Read more
1.91.0 · Source§

impl PartialEq<PathBuf> for String

Source§

fn eq(&self, other: &PathBuf) -> bool

Equality operator ==. Read more
1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Inequality operator !=. Read more
Source§

impl PartialEq<SmolStr> for String

Source§

fn eq(&self, other: &SmolStr) -> bool

Equality operator ==. Read more
1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Inequality operator !=. Read more
Source§

impl<'a> PartialEq<SmolStr> for &'a String

Source§

fn eq(&self, other: &SmolStr) -> bool

Equality operator ==. Read more
1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Inequality operator !=. Read more
1.0.0 · Source§

impl PartialEq<String> for Cow<'_, str>

Source§

fn eq(&self, other: &String) -> bool

Equality operator ==. Read more
Source§

fn ne(&self, other: &String) -> bool

Inequality operator !=. Read more
Source§

impl<const N: usize> PartialEq<TinyAsciiStr<N>> for String

Available on crate feature alloc only.
Source§

fn eq(&self, other: &TinyAsciiStr<N>) -> bool

Equality operator ==. Read more
1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Inequality operator !=. Read more
Source§

impl PartialEq<Value> for String

Source§

fn eq(&self, other: &Value) -> bool

Equality operator ==. Read more
1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Inequality operator !=. Read more
1.0.0 · Source§

impl PartialEq<str> for String

Source§

fn eq(&self, other: &str) -> bool

Equality operator ==. Read more
Source§

fn ne(&self, other: &str) -> bool

Inequality operator !=. Read more
1.0.0 · Source§

impl PartialOrd for String

Source§

fn partial_cmp(&self, other: &String) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
1.0.0 (const: unstable) · Source§

fn lt(&self, other: &Rhs) -> bool

Tests less than (for self and other) and is used by the < operator. Read more
1.0.0 (const: unstable) · Source§

fn le(&self, other: &Rhs) -> bool

Tests less than or equal to (for self and other) and is used by the <= operator. Read more
1.0.0 (const: unstable) · Source§

fn gt(&self, other: &Rhs) -> bool

Tests greater than (for self and other) and is used by the > operator. Read more
1.0.0 (const: unstable) · Source§

fn ge(&self, other: &Rhs) -> bool

Tests greater than or equal to (for self and other) and is used by the >= operator. Read more
Source§

impl PartialOrd<Authority> for String

Source§

fn partial_cmp(&self, other: &Authority) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
1.0.0 (const: unstable) · Source§

fn lt(&self, other: &Rhs) -> bool

Tests less than (for self and other) and is used by the < operator. Read more
1.0.0 (const: unstable) · Source§

fn le(&self, other: &Rhs) -> bool

Tests less than or equal to (for self and other) and is used by the <= operator. Read more
1.0.0 (const: unstable) · Source§

fn gt(&self, other: &Rhs) -> bool

Tests greater than (for self and other) and is used by the > operator. Read more
1.0.0 (const: unstable) · Source§

fn ge(&self, other: &Rhs) -> bool

Tests greater than or equal to (for self and other) and is used by the >= operator. Read more
Source§

impl PartialOrd<Bytes> for String

Source§

fn partial_cmp(&self, other: &Bytes) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
1.0.0 (const: unstable) · Source§

fn lt(&self, other: &Rhs) -> bool

Tests less than (for self and other) and is used by the < operator. Read more
1.0.0 (const: unstable) · Source§

fn le(&self, other: &Rhs) -> bool

Tests less than or equal to (for self and other) and is used by the <= operator. Read more
1.0.0 (const: unstable) · Source§

fn gt(&self, other: &Rhs) -> bool

Tests greater than (for self and other) and is used by the > operator. Read more
1.0.0 (const: unstable) · Source§

fn ge(&self, other: &Rhs) -> bool

Tests greater than or equal to (for self and other) and is used by the >= operator. Read more
Source§

impl PartialOrd<BytesMut> for String

Source§

fn partial_cmp(&self, other: &BytesMut) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
1.0.0 (const: unstable) · Source§

fn lt(&self, other: &Rhs) -> bool

Tests less than (for self and other) and is used by the < operator. Read more
1.0.0 (const: unstable) · Source§

fn le(&self, other: &Rhs) -> bool

Tests less than or equal to (for self and other) and is used by the <= operator. Read more
1.0.0 (const: unstable) · Source§

fn gt(&self, other: &Rhs) -> bool

Tests greater than (for self and other) and is used by the > operator. Read more
1.0.0 (const: unstable) · Source§

fn ge(&self, other: &Rhs) -> bool

Tests greater than or equal to (for self and other) and is used by the >= operator. Read more
Source§

impl PartialOrd<HeaderValue> for String

Source§

fn partial_cmp(&self, other: &HeaderValue) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
1.0.0 (const: unstable) · Source§

fn lt(&self, other: &Rhs) -> bool

Tests less than (for self and other) and is used by the < operator. Read more
1.0.0 (const: unstable) · Source§

fn le(&self, other: &Rhs) -> bool

Tests less than or equal to (for self and other) and is used by the <= operator. Read more
1.0.0 (const: unstable) · Source§

fn gt(&self, other: &Rhs) -> bool

Tests greater than (for self and other) and is used by the > operator. Read more
1.0.0 (const: unstable) · Source§

fn ge(&self, other: &Rhs) -> bool

Tests greater than or equal to (for self and other) and is used by the >= operator. Read more
Source§

impl PartialOrd<PathAndQuery> for String

Source§

fn partial_cmp(&self, other: &PathAndQuery) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
1.0.0 (const: unstable) · Source§

fn lt(&self, other: &Rhs) -> bool

Tests less than (for self and other) and is used by the < operator. Read more
1.0.0 (const: unstable) · Source§

fn le(&self, other: &Rhs) -> bool

Tests less than or equal to (for self and other) and is used by the <= operator. Read more
1.0.0 (const: unstable) · Source§

fn gt(&self, other: &Rhs) -> bool

Tests greater than (for self and other) and is used by the > operator. Read more
1.0.0 (const: unstable) · Source§

fn ge(&self, other: &Rhs) -> bool

Tests greater than or equal to (for self and other) and is used by the >= operator. Read more
Source§

impl PartialReflect for String

Source§

fn get_represented_type_info(&self) -> Option<&'static TypeInfo>

Returns the TypeInfo of the type represented by this value. Read more
Source§

fn to_dynamic(&self) -> Box<dyn PartialReflect>

Converts this reflected value into its dynamic representation based on its kind. Read more
Source§

fn try_apply( &mut self, value: &(dyn PartialReflect + 'static), ) -> Result<(), ApplyError>

Tries to apply a reflected value to this value. Read more
Source§

fn reflect_kind(&self) -> ReflectKind

Returns a zero-sized enumeration of “kinds” of type. Read more
Source§

fn reflect_ref(&self) -> ReflectRef<'_>

Returns an immutable enumeration of “kinds” of type. Read more
Source§

fn reflect_mut(&mut self) -> ReflectMut<'_>

Returns a mutable enumeration of “kinds” of type. Read more
Source§

fn reflect_owned(self: Box<String>) -> ReflectOwned

Returns an owned enumeration of “kinds” of type. Read more
Source§

fn try_into_reflect( self: Box<String>, ) -> Result<Box<dyn Reflect>, Box<dyn PartialReflect>>

Attempts to cast this type to a boxed, fully-reflected value.
Source§

fn try_as_reflect(&self) -> Option<&(dyn Reflect + 'static)>

Attempts to cast this type to a fully-reflected value.
Source§

fn try_as_reflect_mut(&mut self) -> Option<&mut (dyn Reflect + 'static)>

Attempts to cast this type to a mutable, fully-reflected value.
Source§

fn into_partial_reflect(self: Box<String>) -> Box<dyn PartialReflect>

Casts this type to a boxed, reflected value. Read more
Source§

fn as_partial_reflect(&self) -> &(dyn PartialReflect + 'static)

Casts this type to a reflected value. Read more
Source§

fn as_partial_reflect_mut(&mut self) -> &mut (dyn PartialReflect + 'static)

Casts this type to a mutable, reflected value. Read more
Source§

fn reflect_hash(&self) -> Option<u64>

Returns a hash of the value (which includes the type). Read more
Source§

fn reflect_partial_eq( &self, value: &(dyn PartialReflect + 'static), ) -> Option<bool>

Returns a “partial equality” comparison result. Read more
Source§

fn reflect_partial_cmp( &self, value: &(dyn PartialReflect + 'static), ) -> Option<Ordering>

Returns a “partial comparison” result. Read more
Source§

fn debug(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Debug formatter for the value. Read more
Source§

fn reflect_clone(&self) -> Result<Box<dyn Reflect>, ReflectCloneError>

Attempts to clone Self using reflection. Read more
Source§

fn apply(&mut self, value: &(dyn PartialReflect + 'static))

Applies a reflected value to this value. Read more
Source§

fn reflect_clone_and_take<T>(&self) -> Result<T, ReflectCloneError>
where T: 'static, Self: Sized + TypePath,

For a type implementing PartialReflect, combines reflect_clone and take in a useful fashion, automatically constructing an appropriate ReflectCloneError if the downcast fails.
Source§

fn is_dynamic(&self) -> bool

Indicates whether or not this type is a dynamic type. Read more
Source§

impl<'b> Pattern for &'b String

A convenience impl that delegates to the impl for &str.

§Examples

assert_eq!(String::from("Hello world").find("world"), Some(6));
Source§

type Searcher<'a> = <&'b str as Pattern>::Searcher<'a>

🔬This is a nightly-only experimental API. (pattern)
Associated searcher for this pattern
Source§

fn into_searcher(self, haystack: &str) -> <&'b str as Pattern>::Searcher<'_>

🔬This is a nightly-only experimental API. (pattern)
Constructs the associated searcher from self and the haystack to search in.
Source§

fn is_contained_in(self, haystack: &str) -> bool

🔬This is a nightly-only experimental API. (pattern)
Checks whether the pattern matches anywhere in the haystack
Source§

fn is_prefix_of(self, haystack: &str) -> bool

🔬This is a nightly-only experimental API. (pattern)
Checks whether the pattern matches at the front of the haystack
Source§

fn strip_prefix_of(self, haystack: &str) -> Option<&str>

🔬This is a nightly-only experimental API. (pattern)
Removes the pattern from the front of haystack, if it matches.
Source§

fn is_suffix_of<'a>(self, haystack: &'a str) -> bool
where <&'b String as Pattern>::Searcher<'a>: ReverseSearcher<'a>,

🔬This is a nightly-only experimental API. (pattern)
Checks whether the pattern matches at the back of the haystack
Source§

fn strip_suffix_of<'a>(self, haystack: &'a str) -> Option<&'a str>
where <&'b String as Pattern>::Searcher<'a>: ReverseSearcher<'a>,

🔬This is a nightly-only experimental API. (pattern)
Removes the pattern from the back of haystack, if it matches.
Source§

fn as_utf8_pattern(&self) -> Option<Utf8Pattern<'_>>

🔬This is a nightly-only experimental API. (pattern)
Returns the pattern as UTF-8 if possible.
Source§

impl PhfBorrow<str> for String

Available on crate feature std only.
Source§

fn borrow(&self) -> &str

Convert a reference to self to a reference to the borrowed type.
Source§

impl PhfHash for String

Available on crate feature std only.
Source§

fn phf_hash<H>(&self, state: &mut H)
where H: Hasher,

Feeds the value into the state given, updating the hasher as necessary.
Source§

fn phf_hash_slice<H>(data: &[Self], state: &mut H)
where H: Hasher, Self: Sized,

Feeds a slice of this type into the state provided.
Source§

impl Reflect for String

Source§

fn into_any(self: Box<String>) -> Box<dyn Any>

Returns the value as a Box<dyn Any>. Read more
Source§

fn as_any(&self) -> &(dyn Any + 'static)

Returns the value as a &dyn Any. Read more
Source§

fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)

Returns the value as a &mut dyn Any. Read more
Source§

fn into_reflect(self: Box<String>) -> Box<dyn Reflect>

Casts this type to a boxed, fully-reflected value.
Source§

fn as_reflect(&self) -> &(dyn Reflect + 'static)

Casts this type to a fully-reflected value.
Source§

fn as_reflect_mut(&mut self) -> &mut (dyn Reflect + 'static)

Casts this type to a mutable, fully-reflected value.
Source§

fn set(&mut self, value: Box<dyn Reflect>) -> Result<(), Box<dyn Reflect>>

Performs a type-checked assignment of a reflected value to this value. Read more
Source§

impl<'a> Replacer for &'a String

Source§

fn replace_append(&mut self, caps: &Captures<'_>, dst: &mut String)

Appends possibly empty data to dst to replace the current match. Read more
Source§

fn no_expansion(&mut self) -> Option<Cow<'_, str>>

Return a fixed unchanging replacement string. Read more
Source§

fn by_ref<'r>(&'r mut self) -> ReplacerRef<'r, Self>

Returns a type that implements Replacer, but that borrows and wraps this Replacer. Read more
Source§

impl Replacer for String

Source§

fn replace_append(&mut self, caps: &Captures<'_>, dst: &mut String)

Appends possibly empty data to dst to replace the current match. Read more
Source§

fn no_expansion(&mut self) -> Option<Cow<'_, str>>

Return a fixed unchanging replacement string. Read more
Source§

fn by_ref<'r>(&'r mut self) -> ReplacerRef<'r, Self>

Returns a type that implements Replacer, but that borrows and wraps this Replacer. Read more
Source§

impl Serialize for String

Available on crate features alloc or std only.
Source§

fn serialize<S>( &self, serializer: S, ) -> Result<<S as Serializer>::Ok, <S as Serializer>::Error>
where S: Serializer,

Serialize this value into the given Serde serializer. Read more
Source§

impl StableDeref for String

Available on crate feature alloc only.
Source§

impl StrConsumer for String

Pushes the str onto the end of the String

Source§

fn consume(&mut self, buf: &str)

Consume the base64 encoded data in buf
Source§

impl<'s> StringBuilder<'s> for String

Available on crate feature alloc only.
Source§

fn clear(&mut self)

Source§

fn push_str(&mut self, append: &'s str) -> bool

Source§

fn push_char(&mut self, append: char) -> bool

1.0.0 · Source§

impl StructuralPartialEq for String

1.16.0 · Source§

impl ToSocketAddrs for String

Source§

type Iter = IntoIter<SocketAddr>

Returned iterator over socket addresses which this type may correspond to.
Source§

fn to_socket_addrs(&self) -> Result<IntoIter<SocketAddr>, Error>

Converts this object to an iterator of resolved SocketAddrs. Read more
Source§

impl ToTokens for String

Source§

fn to_tokens(&self, tokens: &mut TokenStream)

🔬This is a nightly-only experimental API. (proc_macro_totokens)
Write self to the given TokenStream. Read more
Source§

fn to_token_stream(&self) -> TokenStream

🔬This is a nightly-only experimental API. (proc_macro_totokens)
Convert self directly into a TokenStream object. Read more
Source§

fn into_token_stream(self) -> TokenStream
where Self: Sized,

🔬This is a nightly-only experimental API. (proc_macro_totokens)
Convert self directly into a TokenStream object. Read more
Source§

impl ToTokens for String

Source§

fn to_tokens(&self, tokens: &mut TokenStream)

Write self to the given TokenStream. Read more
Source§

fn to_token_stream(&self) -> TokenStream

Convert self directly into a TokenStream object. Read more
Source§

fn into_token_stream(self) -> TokenStream
where Self: Sized,

Convert self directly into a TokenStream object. Read more
Source§

impl<'a> TryFrom<&'a ByteStr> for String

Source§

type Error = Utf8Error

The type returned in the event of a conversion error.
Source§

fn try_from( s: &'a ByteStr, ) -> Result<String, <String as TryFrom<&'a ByteStr>>::Error>

Performs the conversion.
Source§

impl TryFrom<&Value<'_>> for String

Source§

type Error = Error

The type returned in the event of a conversion error.
Source§

fn try_from( value: &Value<'_>, ) -> Result<String, <String as TryFrom<&Value<'_>>>::Error>

Performs the conversion.
Source§

impl TryFrom<ByteString> for String

Source§

type Error = FromUtf8Error

The type returned in the event of a conversion error.
Source§

fn try_from( s: ByteString, ) -> Result<String, <String as TryFrom<ByteString>>::Error>

Performs the conversion.
1.85.0 · Source§

impl TryFrom<CString> for String

Source§

fn try_from( value: CString, ) -> Result<String, <String as TryFrom<CString>>::Error>

Converts a CString into a String if it contains valid UTF-8 data.

This method is equivalent to CString::into_string.

Source§

type Error = IntoStringError

The type returned in the event of a conversion error.
Source§

impl TryFrom<OwnedValue> for String

Source§

type Error = Error

The type returned in the event of a conversion error.
Source§

fn try_from( v: OwnedValue, ) -> Result<String, <String as TryFrom<OwnedValue>>::Error>

Performs the conversion.
Source§

impl TryFrom<String> for Uuid

Available on crate feature std only.
Source§

type Error = Error

The type returned in the event of a conversion error.
Source§

fn try_from(uuid_str: String) -> Result<Uuid, <Uuid as TryFrom<String>>::Error>

Performs the conversion.
Source§

impl<'a> TryFrom<Value<'a>> for String

Source§

type Error = Error

The type returned in the event of a conversion error.
Source§

fn try_from( value: Value<'a>, ) -> Result<String, <String as TryFrom<Value<'a>>>::Error>

Performs the conversion.
1.87.0 · Source§

impl TryFrom<Vec<u8>> for String

Source§

fn try_from( bytes: Vec<u8>, ) -> Result<String, <String as TryFrom<Vec<u8>>>::Error>

Converts the given Vec<u8> into a String if it contains valid UTF-8 data.

§Examples
let s1 = b"hello world".to_vec();
let v1 = String::try_from(s1).unwrap();
assert_eq!(v1, "hello world");
Source§

type Error = FromUtf8Error

The type returned in the event of a conversion error.
Source§

impl Type for String

Source§

const SIGNATURE: &'static Signature

The signature for the implementing type, in parsed format. Read more
Source§

impl TypePath for String

Source§

fn type_path() -> &'static str

Returns the fully qualified path of the underlying type. Read more
Source§

fn short_type_path() -> &'static str

Returns a short, pretty-print enabled path to the type. Read more
Source§

fn type_ident() -> Option<&'static str>

Returns the name of the type, or None if it is anonymous. Read more
Source§

fn crate_name() -> Option<&'static str>

Returns the name of the crate the type is in, or None if it is anonymous. Read more
Source§

fn module_path() -> Option<&'static str>

Returns the path to the module the type is in, or None if it is anonymous. Read more
Source§

impl Typed for String

Source§

fn type_info() -> &'static TypeInfo

Returns the compile-time info for the underlying type.
Source§

impl Validate for String

Source§

fn validate<P, R>(&self, _root: &Root, _path: P, _report: &mut R)
where P: Fn() -> Path, R: FnMut(&dyn Fn() -> Path, Error),

Validates the invariants required for the library to function safely.
Source§

impl Value for String

Source§

fn record(&self, key: &Field, visitor: &mut dyn Visit)

Visits this value with the given Visitor.
1.0.0 · Source§

impl Write for String

Available on non-no_global_oom_handling only.
Source§

fn write_str(&mut self, s: &str) -> Result<(), Error>

Writes a string slice into this writer, returning whether the write succeeded. Read more
Source§

fn write_char(&mut self, c: char) -> Result<(), Error>

Writes a char into this writer, returning whether the write succeeded. Read more
1.0.0 · Source§

fn write_fmt(&mut self, args: Arguments<'_>) -> Result<(), Error>

Glue for usage of the write! macro with implementors of this trait. Read more
Source§

impl WriteTomlKey for String

Available on crate feature alloc only.
Source§

fn write_toml_key<W>(&self, writer: &mut W) -> Result<(), Error>
where W: TomlWrite + ?Sized,

Source§

impl WriteTomlValue for String

Available on crate feature alloc only.
Source§

fn write_toml_value<W>(&self, writer: &mut W) -> Result<(), Error>
where W: TomlWrite + ?Sized,

Source§

impl Writeable for String

Available on crate feature alloc only.
Source§

fn write_to<W>(&self, sink: &mut W) -> Result<(), Error>
where W: Write + ?Sized,

Writes a string to the given sink. Errors from the sink are bubbled up. The default implementation delegates to write_to_parts, and discards any Part annotations.
Source§

fn writeable_length_hint(&self) -> LengthHint

Returns a hint for the number of UTF-8 bytes that will be written to the sink. Read more
Source§

fn writeable_borrow(&self) -> Option<&str>

Returns a &str that matches the output of write_to, if possible. Read more
Source§

fn write_to_parts<S>(&self, sink: &mut S) -> Result<(), Error>
where S: PartsWrite + ?Sized,

Write bytes and Part annotations to the given sink. Errors from the sink are bubbled up. The default implementation delegates to write_to, and doesn’t produce any Part annotations.
Source§

fn write_to_string(&self) -> Cow<'_, str>

Creates a new string with the data from this Writeable. Read more
Source§

impl<'zf> ZeroFrom<'zf, String> for Cow<'zf, str>

Available on crate feature alloc only.
Source§

fn zero_from(other: &'zf String) -> Cow<'zf, str>

Clone the other C into a struct that may retain references into C.
Source§

impl Zeroize for String

Available on crate feature alloc only.
Source§

fn zeroize(&mut self)

Zero out this object from memory using Rust intrinsics which ensure the zeroization operation is not “optimized away” by the compiler.

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T, U> AsBindGroupShaderType<U> for T
where U: ShaderType, &'a T: for<'a> Into<U>,

Source§

fn as_bind_group_shader_type(&self, _images: &RenderAssets<GpuImage>) -> U

Return the T ShaderType for self. When used in AsBindGroup derives, it is safe to assume that all images in self exist.
Source§

impl<A, T> AsBits<T> for A
where A: AsRef<[T]>, T: BitStore,

Source§

fn as_bits<O>(&self) -> &BitSlice<T, O>
where O: BitOrder,

Views self as an immutable bit-slice region with the O ordering.
Source§

fn try_as_bits<O>(&self) -> Result<&BitSlice<T, O>, BitSpanError<T>>
where O: BitOrder,

Attempts to view self as an immutable bit-slice region with the O ordering. Read more
Source§

impl<T> BodyExt for T
where T: Body + ?Sized,

Source§

fn frame(&mut self) -> Frame<'_, Self>
where Self: Unpin,

Returns a future that resolves to the next Frame, if any.
Source§

fn map_frame<F, B>(self, f: F) -> MapFrame<Self, F>
where Self: Sized, F: FnMut(Frame<Self::Data>) -> Frame<B>, B: Buf,

Maps this body’s frame to a different kind.
Source§

fn inspect_frame<F>(self, f: F) -> InspectFrame<Self, F>
where Self: Sized, F: FnMut(&Frame<Self::Data>),

A body that calls a function with a reference to each frame before yielding it.
Source§

fn map_err<F, E>(self, f: F) -> MapErr<Self, F>
where Self: Sized, F: FnMut(Self::Error) -> E,

Maps this body’s error value to a different value.
Source§

fn inspect_err<F>(self, f: F) -> InspectErr<Self, F>
where Self: Sized, F: FnMut(&Self::Error),

A body that calls a function with a reference to an error before yielding it.
Source§

fn boxed(self) -> BoxBody<Self::Data, Self::Error>
where Self: Sized + Send + Sync + 'static,

Turn this body into a boxed trait object.
Source§

fn boxed_unsync(self) -> UnsyncBoxBody<Self::Data, Self::Error>
where Self: Sized + Send + 'static,

Turn this body into a boxed trait object that is !Sync.
Source§

fn collect(self) -> Collect<Self>
where Self: Sized,

Turn this body into Collected body which will collect all the DATA frames and trailers.
Source§

fn with_trailers<F>(self, trailers: F) -> WithTrailers<Self, F>
where Self: Sized, F: Future<Output = Option<Result<HeaderMap, Self::Error>>>,

Add trailers to the body. Read more
Source§

fn into_stream(self) -> BodyStream<Self>
where Self: Sized,

Turn this body into BodyStream.
Source§

fn into_data_stream(self) -> BodyDataStream<Self>
where Self: Sized,

Turn this body into BodyDataStream.
Source§

fn fuse(self) -> Fuse<Self>
where Self: Sized,

Creates a “fused” body. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> Brush for T
where T: Clone + PartialEq + Default + Debug,

Source§

impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<T> CheapCloneStr for T
where T: AsRef<str> + for<'a> From<&'a str> + From<String> + PartialEq + Eq + Clone + Default + Debug + 'static,

Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<Q, K> Comparable<K> for Q
where Q: Ord + ?Sized, K: Borrow<Q> + ?Sized,

Source§

fn compare(&self, key: &K) -> Ordering

Compare self to key and return their ordering.
Source§

impl<T> ConditionalSend for T
where T: Send,

Source§

impl<T> Conv for T

Source§

fn conv<T>(self) -> T
where Self: Into<T>,

Converts self into T using Into<T>. Read more
Source§

impl<T> DeserializeOwned for T
where T: for<'de> Deserialize<'de>,

Source§

impl<T> Downcast for T
where T: Any,

Source§

fn into_any(self: Box<T>) -> Box<dyn Any>

Converts Box<dyn Trait> (where Trait: Downcast) to Box<dyn Any>, which can then be downcast into Box<dyn ConcreteType> where ConcreteType implements Trait.
Source§

fn into_any_rc(self: Rc<T>) -> Rc<dyn Any>

Converts Rc<Trait> (where Trait: Downcast) to Rc<Any>, which can then be further downcast into Rc<ConcreteType> where ConcreteType implements Trait.
Source§

fn as_any(&self) -> &(dyn Any + 'static)

Converts &Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot generate &Any’s vtable from &Trait’s.
Source§

fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)

Converts &mut Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot generate &mut Any’s vtable from &mut Trait’s.
Source§

impl<T> Downcast for T
where T: Any,

Source§

fn into_any(self: Box<T>) -> Box<dyn Any>

Convert Box<dyn Trait> (where Trait: Downcast) to Box<dyn Any>. Box<dyn Any> can then be further downcast into Box<ConcreteType> where ConcreteType implements Trait.
Source§

fn into_any_rc(self: Rc<T>) -> Rc<dyn Any>

Convert Rc<Trait> (where Trait: Downcast) to Rc<Any>. Rc<Any> can then be further downcast into Rc<ConcreteType> where ConcreteType implements Trait.
Source§

fn as_any(&self) -> &(dyn Any + 'static)

Convert &Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot generate &Any’s vtable from &Trait’s.
Source§

fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)

Convert &mut Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot generate &mut Any’s vtable from &mut Trait’s.
Source§

impl<T> DowncastSend for T
where T: Any + Send,

Source§

fn into_any_send(self: Box<T>) -> Box<dyn Any + Send>

Converts Box<Trait> (where Trait: DowncastSend) to Box<dyn Any + Send>, which can then be downcast into Box<ConcreteType> where ConcreteType implements Trait.
Source§

impl<T> DowncastSync for T
where T: Any + Send + Sync,

Source§

fn into_any_arc(self: Arc<T>) -> Arc<dyn Any + Sync + Send>

Convert Arc<Trait> (where Trait: Downcast) to Arc<Any>. Arc<Any> can then be further downcast into Arc<ConcreteType> where ConcreteType implements Trait.
Source§

impl<S, T> Duplex<S> for T
where T: FromSample<S> + ToSample<S>,

Source§

impl<T> DynEq for T
where T: Any + Eq,

Source§

fn dyn_eq(&self, other: &(dyn DynEq + 'static)) -> bool

This method tests for self and other values to be equal. Read more
Source§

impl<T> DynHash for T
where T: DynEq + Hash,

Source§

fn dyn_hash(&self, state: &mut dyn Hasher)

Feeds this value into the given Hasher.
Source§

impl<'de, T> DynamicDeserialize<'de> for T
where T: Type + Deserialize<'de>,

Source§

type Deserializer = PhantomData<T>

A DeserializeSeed implementation for this type.
Source§

fn deserializer_for_signature( signature: &Signature, ) -> Result<<T as DynamicDeserialize<'de>>::Deserializer, Error>

Get a deserializer compatible with this parsed signature.
Source§

impl<T> DynamicType for T
where T: Type + ?Sized,

Source§

fn signature(&self) -> Signature

The type signature for self. Read more
Source§

impl<T> DynamicTypePath for T
where T: TypePath,

Source§

impl<T> DynamicTyped for T
where T: Typed,

Source§

impl<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

Source§

fn equivalent(&self, key: &K) -> bool

Compare self to key and return true if they are equal.
Source§

impl<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

Source§

fn equivalent(&self, key: &K) -> bool

Checks if this value is equivalent to the given key. Read more
Source§

impl<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

Source§

fn equivalent(&self, key: &K) -> bool

Checks if this value is equivalent to the given key. Read more
Source§

impl<T> ErasedDestructor for T
where T: 'static,

Source§

impl<T> FmtForward for T

Source§

fn fmt_binary(self) -> FmtBinary<Self>
where Self: Binary,

Causes self to use its Binary implementation when Debug-formatted.
Source§

fn fmt_display(self) -> FmtDisplay<Self>
where Self: Display,

Causes self to use its Display implementation when Debug-formatted.
Source§

fn fmt_lower_exp(self) -> FmtLowerExp<Self>
where Self: LowerExp,

Causes self to use its LowerExp implementation when Debug-formatted.
Source§

fn fmt_lower_hex(self) -> FmtLowerHex<Self>
where Self: LowerHex,

Causes self to use its LowerHex implementation when Debug-formatted.
Source§

fn fmt_octal(self) -> FmtOctal<Self>
where Self: Octal,

Causes self to use its Octal implementation when Debug-formatted.
Source§

fn fmt_pointer(self) -> FmtPointer<Self>
where Self: Pointer,

Causes self to use its Pointer implementation when Debug-formatted.
Source§

fn fmt_upper_exp(self) -> FmtUpperExp<Self>
where Self: UpperExp,

Causes self to use its UpperExp implementation when Debug-formatted.
Source§

fn fmt_upper_hex(self) -> FmtUpperHex<Self>
where Self: UpperHex,

Causes self to use its UpperHex implementation when Debug-formatted.
Source§

fn fmt_list(self) -> FmtList<Self>
where &'a Self: for<'a> IntoIterator,

Formats each item in a sequence. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<S> FromSample<S> for S

Source§

fn from_sample_(s: S) -> S

Source§

impl<T> FromTemplate for T
where T: Clone + Default + Unpin,

Source§

type Template = T

The Template for this type.
Source§

impl<T> FromWorld for T
where T: Default,

Source§

fn from_world(_world: &mut World) -> T

Creates Self using default().

Source§

impl<T> GetPath for T
where T: Reflect + ?Sized,

Source§

fn reflect_path<'p>( &self, path: impl ReflectPath<'p>, ) -> Result<&(dyn PartialReflect + 'static), ReflectPathError<'p>>

Returns a reference to the value specified by path. Read more
Source§

fn reflect_path_mut<'p>( &mut self, path: impl ReflectPath<'p>, ) -> Result<&mut (dyn PartialReflect + 'static), ReflectPathError<'p>>

Returns a mutable reference to the value specified by path. Read more
Source§

fn path<'p, T>( &self, path: impl ReflectPath<'p>, ) -> Result<&T, ReflectPathError<'p>>
where T: Reflect,

Returns a statically typed reference to the value specified by path. Read more
Source§

fn path_mut<'p, T>( &mut self, path: impl ReflectPath<'p>, ) -> Result<&mut T, ReflectPathError<'p>>
where T: Reflect,

Returns a statically typed mutable reference to the value specified by path. Read more
Source§

impl<T, W> HasTypeWitness<W> for T
where W: MakeTypeWitness<Arg = T>, T: ?Sized,

Source§

const WITNESS: W = W::MAKE

A constant of the type witness
Source§

impl<T> HitDataExtra for T
where T: Send + Sync + Debug + Any + 'static,

Source§

impl<T> Identity for T
where T: ?Sized,

Source§

const TYPE_EQ: TypeEq<T, <T as Identity>::Type> = TypeEq::NEW

Proof that Self is the same type as Self::Type, provides methods for casting between Self and Self::Type.
Source§

type Type = T

The same type as Self, used to emulate type equality bounds (T == U) with associated type equality constraints (T: Identity<Type = U>).
Source§

impl<T> InitializeFromFunction<T> for T

Source§

fn initialize_from_function(f: fn() -> T) -> T

Create an instance of this type from an initialization function
Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> IntoResult<T> for T

Source§

fn into_result(self) -> Result<T, RunSystemError>

Converts this type into the system output type.
Source§

impl<F, T> IntoSample<T> for F
where T: FromSample<F>,

Source§

fn into_sample(self) -> T

Source§

impl<A> Is for A
where A: Any,

Source§

fn is<T>() -> bool
where T: Any,

Checks if the current type “is” another type, using a TypeId equality comparison. This is most useful in the context of generic logic. Read more
Source§

impl<T> NoneValue for T
where T: Default,

Source§

type NoneType = T

Source§

fn null_value() -> T

The none-equivalent value.
Source§

impl<S, T> ParallelSlice<T> for S
where T: Sync, S: AsRef<[T]>,

Source§

fn par_chunk_map<F, R>( &self, task_pool: &TaskPool, chunk_size: usize, f: F, ) -> Vec<R>
where F: Fn(usize, &[T]) -> R + Send + Sync, R: Send + 'static,

Splits the slice in chunks of size chunks_size or less and maps the chunks in parallel across the provided task_pool. One task is spawned in the task pool for every chunk. Read more
Source§

fn par_splat_map<F, R>( &self, task_pool: &TaskPool, max_tasks: Option<usize>, f: F, ) -> Vec<R>
where F: Fn(usize, &[T]) -> R + Send + Sync, R: Send + 'static,

Splits the slice into a maximum of max_tasks chunks, and maps the chunks in parallel across the provided task_pool. One task is spawned in the task pool for every chunk. Read more
Source§

impl<G> PatchFromTemplate for G
where G: FromTemplate,

Source§

type Template = <G as FromTemplate>::Template

The Template that will be patched.
Source§

fn patch<F>(func: F) -> TemplatePatch<F, <G as PatchFromTemplate>::Template>
where F: FnOnce(&mut <G as PatchFromTemplate>::Template, &mut ResolveContext<'_>),

Takes a “patch function” func, and turns it into a TemplatePatch.
Source§

impl<T> PatchTemplate for T
where T: Template,

Source§

fn patch_template<F>(func: F) -> TemplatePatch<F, T>
where F: FnOnce(&mut T, &mut ResolveContext<'_>),

Takes a “patch function” func that patches this Template, and turns it into a TemplatePatch.
Source§

impl<T> Pipe for T
where T: ?Sized,

Source§

fn pipe<R>(self, func: impl FnOnce(Self) -> R) -> R
where Self: Sized,

Pipes by value. This is generally the method you want to use. Read more
Source§

fn pipe_ref<'a, R>(&'a self, func: impl FnOnce(&'a Self) -> R) -> R
where R: 'a,

Borrows self and passes that borrow into the pipe function. Read more
Source§

fn pipe_ref_mut<'a, R>(&'a mut self, func: impl FnOnce(&'a mut Self) -> R) -> R
where R: 'a,

Mutably borrows self and passes that borrow into the pipe function. Read more
Source§

fn pipe_borrow<'a, B, R>(&'a self, func: impl FnOnce(&'a B) -> R) -> R
where Self: Borrow<B>, B: 'a + ?Sized, R: 'a,

Borrows self, then passes self.borrow() into the pipe function. Read more
Source§

fn pipe_borrow_mut<'a, B, R>( &'a mut self, func: impl FnOnce(&'a mut B) -> R, ) -> R
where Self: BorrowMut<B>, B: 'a + ?Sized, R: 'a,

Mutably borrows self, then passes self.borrow_mut() into the pipe function. Read more
Source§

fn pipe_as_ref<'a, U, R>(&'a self, func: impl FnOnce(&'a U) -> R) -> R
where Self: AsRef<U>, U: 'a + ?Sized, R: 'a,

Borrows self, then passes self.as_ref() into the pipe function.
Source§

fn pipe_as_mut<'a, U, R>(&'a mut self, func: impl FnOnce(&'a mut U) -> R) -> R
where Self: AsMut<U>, U: 'a + ?Sized, R: 'a,

Mutably borrows self, then passes self.as_mut() into the pipe function.
Source§

fn pipe_deref<'a, T, R>(&'a self, func: impl FnOnce(&'a T) -> R) -> R
where Self: Deref<Target = T>, T: 'a + ?Sized, R: 'a,

Borrows self, then passes self.deref() into the pipe function.
Source§

fn pipe_deref_mut<'a, T, R>( &'a mut self, func: impl FnOnce(&'a mut T) -> R, ) -> R
where Self: DerefMut<Target = T> + Deref, T: 'a + ?Sized, R: 'a,

Mutably borrows self, then passes self.deref_mut() into the pipe function.
Source§

impl<T> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

Source§

impl<R, P> ReadPrimitive<R> for P
where R: Read + ReadEndian<P>, P: Default,

Source§

fn read_from_little_endian(read: &mut R) -> Result<Self, Error>

Read this value from the supplied reader. Same as ReadEndian::read_from_little_endian().
Source§

fn read_from_big_endian(read: &mut R) -> Result<Self, Error>

Read this value from the supplied reader. Same as ReadEndian::read_from_big_endian().
Source§

fn read_from_native_endian(read: &mut R) -> Result<Self, Error>

Read this value from the supplied reader. Same as ReadEndian::read_from_native_endian().
Source§

impl<P, T> Receiver for P
where P: Deref<Target = T> + ?Sized, T: ?Sized,

Source§

type Target = T

🔬This is a nightly-only experimental API. (arbitrary_self_types)
The target type on which the method may be called.
Source§

impl<T> Reflectable for T

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> Serialize for T
where T: Serialize + ?Sized,

Source§

fn erased_serialize(&self, serializer: &mut dyn Serializer) -> Result<(), Error>

Source§

fn do_erased_serialize( &self, serializer: &mut dyn Serializer, ) -> Result<(), ErrorImpl>

Source§

impl<T> Settings for T
where T: 'static + Send + Sync,

Source§

impl<T> Source for T
where T: Deref, <T as Deref>::Target: Source,

Source§

type Slice<'a> = <<T as Deref>::Target as Source>::Slice<'a> where T: 'a

A type this Source can be sliced into.
Source§

fn len(&self) -> usize

Length of the source
Source§

fn read<'a, Chunk>(&'a self, offset: usize) -> Option<Chunk>
where Chunk: Chunk<'a>,

Read a chunk of bytes into an array. Returns None when reading out of bounds would occur. Read more
Source§

fn slice(&self, range: Range<usize>) -> Option<<T as Source>::Slice<'_>>

Get a slice of the source at given range. This is analogous to slice::get(range). Read more
Source§

unsafe fn slice_unchecked( &self, range: Range<usize>, ) -> <T as Source>::Slice<'_>

Available on non-crate feature forbid_unsafe only.
Get a slice of the source at given range. This is analogous to slice::get_unchecked(range). Read more
Source§

fn is_boundary(&self, index: usize) -> bool

Check if index is valid for this Source, that is: Read more
Source§

fn find_boundary(&self, index: usize) -> usize

For &str sources attempts to find the closest char boundary at which source can be sliced, starting from index. Read more
Source§

impl<T> Spanned for T
where T: Spanned + ?Sized,

Source§

fn span(&self) -> Span

Returns a Span covering the complete contents of this syntax tree node, or Span::call_site() if this node is empty.
Source§

impl<Ret> SpawnIfAsync<(), Ret> for Ret

Source§

fn spawn(self) -> Ret

Spawn the value into the dioxus runtime if it is an async block
Source§

impl<T, O> SuperFrom<T> for O
where O: From<T>,

Source§

fn super_from(input: T) -> O

Convert from a type to another type.
Source§

impl<T, O, M> SuperInto<O, M> for T
where O: SuperFrom<T, M>,

Source§

fn super_into(self) -> O

Convert from a type to another type.
Source§

impl<T> Tap for T

Source§

fn tap(self, func: impl FnOnce(&Self)) -> Self

Immutable access to a value. Read more
Source§

fn tap_mut(self, func: impl FnOnce(&mut Self)) -> Self

Mutable access to a value. Read more
Source§

fn tap_borrow<B>(self, func: impl FnOnce(&B)) -> Self
where Self: Borrow<B>, B: ?Sized,

Immutable access to the Borrow<B> of a value. Read more
Source§

fn tap_borrow_mut<B>(self, func: impl FnOnce(&mut B)) -> Self
where Self: BorrowMut<B>, B: ?Sized,

Mutable access to the BorrowMut<B> of a value. Read more
Source§

fn tap_ref<R>(self, func: impl FnOnce(&R)) -> Self
where Self: AsRef<R>, R: ?Sized,

Immutable access to the AsRef<R> view of a value. Read more
Source§

fn tap_ref_mut<R>(self, func: impl FnOnce(&mut R)) -> Self
where Self: AsMut<R>, R: ?Sized,

Mutable access to the AsMut<R> view of a value. Read more
Source§

fn tap_deref<T>(self, func: impl FnOnce(&T)) -> Self
where Self: Deref<Target = T>, T: ?Sized,

Immutable access to the Deref::Target of a value. Read more
Source§

fn tap_deref_mut<T>(self, func: impl FnOnce(&mut T)) -> Self
where Self: DerefMut<Target = T> + Deref, T: ?Sized,

Mutable access to the Deref::Target of a value. Read more
Source§

fn tap_dbg(self, func: impl FnOnce(&Self)) -> Self

Calls .tap() only in debug builds, and is erased in release builds.
Source§

fn tap_mut_dbg(self, func: impl FnOnce(&mut Self)) -> Self

Calls .tap_mut() only in debug builds, and is erased in release builds.
Source§

fn tap_borrow_dbg<B>(self, func: impl FnOnce(&B)) -> Self
where Self: Borrow<B>, B: ?Sized,

Calls .tap_borrow() only in debug builds, and is erased in release builds.
Source§

fn tap_borrow_mut_dbg<B>(self, func: impl FnOnce(&mut B)) -> Self
where Self: BorrowMut<B>, B: ?Sized,

Calls .tap_borrow_mut() only in debug builds, and is erased in release builds.
Source§

fn tap_ref_dbg<R>(self, func: impl FnOnce(&R)) -> Self
where Self: AsRef<R>, R: ?Sized,

Calls .tap_ref() only in debug builds, and is erased in release builds.
Source§

fn tap_ref_mut_dbg<R>(self, func: impl FnOnce(&mut R)) -> Self
where Self: AsMut<R>, R: ?Sized,

Calls .tap_ref_mut() only in debug builds, and is erased in release builds.
Source§

fn tap_deref_dbg<T>(self, func: impl FnOnce(&T)) -> Self
where Self: Deref<Target = T>, T: ?Sized,

Calls .tap_deref() only in debug builds, and is erased in release builds.
Source§

fn tap_deref_mut_dbg<T>(self, func: impl FnOnce(&mut T)) -> Self
where Self: DerefMut<Target = T> + Deref, T: ?Sized,

Calls .tap_deref_mut() only in debug builds, and is erased in release builds.
Source§

impl<T> Template for T
where T: Clone + Default + Unpin,

Source§

type Output = T

The type of value produced by this Template.
Source§

fn build_template( &self, _context: &mut TemplateContext<'_, '_>, ) -> Result<<T as Template>::Output, BevyError>

Uses this template and the given entity context to produce a Template::Output.
Source§

fn clone_template(&self) -> T

Clones this template. See Clone.
Source§

impl<T> ToHex for T
where T: AsRef<[u8]>,

Source§

fn encode_hex<U>(&self) -> U
where U: FromIterator<char>,

Encode the hex strict representing self into the result. Lower case letters are used (e.g. f9b4ca)
Source§

fn encode_hex_upper<U>(&self) -> U
where U: FromIterator<char>,

Encode the hex strict representing self into the result. Upper case letters are used (e.g. F9B4CA)
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> ToSample<U> for T
where U: FromSample<T>,

Source§

fn to_sample_(self) -> U

Source§

impl<T> ToSmolStr for T
where T: Display + ?Sized,

Source§

impl<T> ToString for T
where T: Display + ?Sized,

Source§

fn to_string(&self) -> String

Converts the given value to a String. Read more
Source§

impl<T> ToTomlKey for T
where T: WriteTomlKey + ?Sized,

Source§

impl<T> ToTomlValue for T
where T: WriteTomlValue + ?Sized,

Source§

impl<W> TomlWrite for W
where W: Write,

Source§

fn open_table_header(&mut self) -> Result<(), Error>

Source§

fn close_table_header(&mut self) -> Result<(), Error>

Source§

fn open_array_of_tables_header(&mut self) -> Result<(), Error>

Source§

fn close_array_of_tables_header(&mut self) -> Result<(), Error>

Source§

fn open_inline_table(&mut self) -> Result<(), Error>

Source§

fn close_inline_table(&mut self) -> Result<(), Error>

Source§

fn open_array(&mut self) -> Result<(), Error>

Source§

fn close_array(&mut self) -> Result<(), Error>

Source§

fn key_sep(&mut self) -> Result<(), Error>

Source§

fn keyval_sep(&mut self) -> Result<(), Error>

Source§

fn key(&mut self, value: impl WriteTomlKey) -> Result<(), Error>

Write an encoded TOML key Read more
Source§

fn value(&mut self, value: impl WriteTomlValue) -> Result<(), Error>

Write an encoded TOML scalar value Read more
Source§

fn val_sep(&mut self) -> Result<(), Error>

Source§

fn space(&mut self) -> Result<(), Error>

Source§

fn open_comment(&mut self) -> Result<(), Error>

Source§

fn newline(&mut self) -> Result<(), Error>

Source§

impl<T> TryConv for T

Source§

fn try_conv<T>(self) -> Result<T, Self::Error>
where Self: TryInto<T>,

Attempts to convert self into T using TryInto<T>. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> TypeData for T
where T: 'static + Send + Sync + Clone,

Source§

fn clone_type_data(&self) -> Box<dyn TypeData>

Creates a type-erased clone of this value.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WasmNotSend for T
where T: Send,

Source§

impl<T> WasmNotSendSync for T

Source§

impl<T> WasmNotSync for T
where T: Sync,

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more