Skip to main content

Text

Struct Text 

Source
pub struct Text(pub String);
Expand description

The top-level UI text component.

Adding Text to an entity will pull in required components for setting up a UI text node.

The string in this component is the first ‘text span’ in a hierarchy of text spans that are collected into a ComputedTextBlock. See TextSpan for the component used by children of entities with Text.

Note that Transform on this entity is managed automatically by the UI layout system.

// Basic usage.
world.spawn(Text::new("hello world!"));

// With non-default style.
world.spawn((
    Text::new("hello world!"),
    TextFont {
        font: font_handle.clone().into(),
        font_size: FontSize::Px(60.0),
        ..Default::default()
    },
    TextColor(BLUE.into()),
));

// With text justification.
world.spawn((
    Text::new("hello world\nand bevy!"),
    TextLayout::justify(Justify::Center)
));

// With spans
world.spawn(Text::new("hello ")).with_children(|parent| {
    parent.spawn(TextSpan::new("world"));
    parent.spawn((TextSpan::new("!"), TextColor(BLUE.into())));
});

Tuple Fields§

§0: String

Implementations§

Source§

impl Text

Source

pub fn new(text: impl Into<String>) -> Text

Makes a new text component.

Examples found in repository?
examples/3d/../helpers/widgets.rs (line 156)
154pub fn ui_text(label: &str, color: Color) -> impl Bundle + use<> {
155    (
156        Text::new(label),
157        TextFont {
158            font_size: FontSize::Px(18.0),
159            ..default()
160        },
161        TextColor(color),
162    )
163}
More examples
Hide additional examples
examples/3d/occlusion_culling.rs (line 378)
376fn spawn_help_text(commands: &mut Commands) {
377    commands.spawn((
378        Text::new(""),
379        Node {
380            position_type: PositionType::Absolute,
381            top: px(12),
382            left: px(12),
383            ..default()
384        },
385    ));
386}
examples/animation/animation_graph.rs (line 260)
258fn setup_help_text(commands: &mut Commands) {
259    commands.spawn((
260        Text::new(HELP_TEXT),
261        Node {
262            position_type: PositionType::Absolute,
263            top: px(12),
264            left: px(12),
265            ..default()
266        },
267    ));
268}
269
270/// Initializes the node UI widgets.
271fn setup_node_rects(commands: &mut Commands) {
272    for (node_rect, node_type) in NODE_RECTS.iter().zip(NODE_TYPES.iter()) {
273        let node_string = match *node_type {
274            NodeType::Clip(ref clip) => clip.text,
275            NodeType::Blend(text) => text,
276        };
277
278        let text = commands
279            .spawn((
280                Text::new(node_string),
281                TextFont {
282                    font_size: FontSize::Px(16.0),
283                    ..default()
284                },
285                TextColor(ANTIQUE_WHITE.into()),
286                TextLayout::justify(Justify::Center),
287            ))
288            .id();
289
290        let container = {
291            let mut container = commands.spawn((
292                Node {
293                    position_type: PositionType::Absolute,
294                    bottom: px(node_rect.bottom),
295                    left: px(node_rect.left),
296                    height: px(node_rect.height),
297                    width: px(node_rect.width),
298                    align_items: AlignItems::Center,
299                    justify_items: JustifyItems::Center,
300                    align_content: AlignContent::Center,
301                    justify_content: JustifyContent::Center,
302                    ..default()
303                },
304                BorderColor::all(WHITE),
305                Outline::new(px(1), Val::ZERO, Color::WHITE),
306            ));
307
308            if let NodeType::Clip(clip) = node_type {
309                container.insert((
310                    Interaction::None,
311                    RelativeCursorPosition::default(),
312                    (*clip).clone(),
313                ));
314            }
315
316            container.id()
317        };
318
319        // Create the background color.
320        if let NodeType::Clip(_) = node_type {
321            let background = commands
322                .spawn((
323                    Node {
324                        position_type: PositionType::Absolute,
325                        top: px(0),
326                        left: px(0),
327                        height: px(node_rect.height),
328                        width: px(node_rect.width),
329                        ..default()
330                    },
331                    BackgroundColor(DARK_GREEN.into()),
332                ))
333                .id();
334
335            commands.entity(container).add_child(background);
336        }
337
338        commands.entity(container).add_child(text);
339    }
340}
examples/3d/specular_tint.rs (line 171)
165    fn create_text(&self) -> Text {
166        let tint_map_help_text = match self.tint_type {
167            TintType::Solid => SWITCH_TO_MAP_HELP_TEXT,
168            TintType::Map => SWITCH_TO_SOLID_TINT_HELP_TEXT,
169        };
170
171        Text::new(tint_map_help_text)
172    }
examples/3d/light_probe_blending.rs (line 379)
377fn spawn_help_text(commands: &mut Commands) {
378    commands.spawn((
379        Text::new(""),
380        Node {
381            position_type: PositionType::Absolute,
382            top: px(12),
383            left: px(12),
384            ..default()
385        },
386        HelpText,
387    ));
388}
389
390/// Moves the sphere a bit every frame.
391fn move_sphere(mut spheres: Query<&mut Transform, With<ReflectiveSphere>>, time: Res<Time>) {
392    let Some(t) = SmoothStepCurve
393        .ping_pong()
394        .unwrap()
395        .forever()
396        .unwrap()
397        .sample(time.elapsed_secs() * SPHERE_MOVEMENT_SPEED)
398    else {
399        return;
400    };
401    for mut sphere_transform in &mut spheres {
402        sphere_transform.translation.z = -ROOM_SEPARATION * t;
403    }
404}
405
406/// Processes requests from the user to move the camera.
407fn orbit_camera(
408    mut cameras: Query<(&mut Transform, &mut OrbitCamera)>,
409    spheres: Query<&Transform, (With<ReflectiveSphere>, Without<OrbitCamera>)>,
410    mouse_buttons: Res<ButtonInput<MouseButton>>,
411    mouse_motion: Res<AccumulatedMouseMotion>,
412    mouse_scroll: Res<AccumulatedMouseScroll>,
413) {
414    // Grab the sphere transform.
415    let Some(sphere_transform) = spheres.iter().next() else {
416        return;
417    };
418
419    for (mut camera_transform, mut orbit_camera) in &mut cameras {
420        // Only pan if the left mouse button is pressed.
421        if mouse_buttons.pressed(MouseButton::Left) {
422            let delta = mouse_motion.delta;
423            orbit_camera.azimuth -= delta.x * CAMERA_ORBIT_SPEED_AZIMUTH;
424            orbit_camera.inclination += delta.y * CAMERA_ORBIT_SPEED_INCLINATION;
425        }
426
427        // Zooming doesn't require a mouse button press, as it uses the mouse
428        // wheel.
429        orbit_camera.radius =
430            (orbit_camera.radius - CAMERA_ZOOM_SPEED * mouse_scroll.delta.y).max(0.01);
431
432        // Calculate the new translation using the [spherical coordinates
433        // formula].
434        //
435        // [spherical coordinates formula]:
436        // https://en.wikipedia.org/wiki/Spherical_coordinate_system#Cartesian_coordinates
437        let new_translation = orbit_camera.radius
438            * vec3(
439                sin(orbit_camera.inclination) * cos(orbit_camera.azimuth),
440                cos(orbit_camera.inclination),
441                sin(orbit_camera.inclination) * sin(orbit_camera.azimuth),
442            );
443
444        // Write in the new transform.
445        *camera_transform =
446            Transform::from_translation(new_translation + sphere_transform.translation)
447                .looking_at(sphere_transform.translation, Vec3::Y);
448    }
449}
450
451/// A system that toggles gizmos on or off when the user clicks on one of the
452/// corresponding radio buttons.
453fn handle_gizmos_enabled_change(
454    mut help_text_query: Query<&mut Text, With<HelpText>>,
455    mut app_status: ResMut<AppStatus>,
456    mut messages: MessageReader<WidgetClickEvent<GizmosEnabled>>,
457) {
458    let mut any_changes = false;
459    for message in messages.read() {
460        app_status.gizmos_enabled = **message;
461        any_changes = true;
462    }
463
464    if any_changes {
465        set_help_text(&app_status, &mut help_text_query);
466    }
467}
468
469/// A system that toggles object visibility when the user clicks on one of the
470/// corresponding radio buttons.
471fn handle_object_to_show_change(
472    mut spheres_query: Query<&mut Visibility, (With<ReflectiveSphere>, Without<ReflectivePrism>)>,
473    mut prisms_query: Query<&mut Visibility, (With<ReflectivePrism>, Without<ReflectiveSphere>)>,
474    mut app_status: ResMut<AppStatus>,
475    mut messages: MessageReader<WidgetClickEvent<ObjectToShow>>,
476) {
477    for message in messages.read() {
478        app_status.object_to_show = **message;
479
480        for mut sphere_visibility in &mut spheres_query {
481            *sphere_visibility = match **message {
482                ObjectToShow::Sphere => Visibility::Inherited,
483                ObjectToShow::Prism => Visibility::Hidden,
484            }
485        }
486        for mut prism_visibility in &mut prisms_query {
487            *prism_visibility = match **message {
488                ObjectToShow::Sphere => Visibility::Hidden,
489                ObjectToShow::Prism => Visibility::Inherited,
490            }
491        }
492    }
493}
494
495/// A system that toggles the camera mode when the user clicks on one of the
496/// corresponding radio buttons.
497fn handle_camera_mode_change(
498    mut commands: Commands,
499    cameras_query: Query<(Entity, &Transform), With<Camera3d>>,
500    sphere_query: Query<&Transform, (With<ReflectiveSphere>, Without<Camera3d>)>,
501    mut help_text_query: Query<&mut Text, With<HelpText>>,
502    mut windows_query: Query<&mut CursorOptions>,
503    mut app_status: ResMut<AppStatus>,
504    mut messages: MessageReader<WidgetClickEvent<CameraMode>>,
505) {
506    let Some(sphere_transform) = sphere_query.iter().next() else {
507        return;
508    };
509
510    let mut any_changes = false;
511    for message in messages.read() {
512        app_status.camera_mode = **message;
513
514        match **message {
515            CameraMode::Orbit => {
516                for (camera_entity, camera_transform) in &cameras_query {
517                    // Convert from Cartesian coordinates back to spherical
518                    // coordinates.
519                    let relative_camera_position =
520                        camera_transform.translation - sphere_transform.translation;
521                    let radius = relative_camera_position.length();
522                    let inclination = atan2(
523                        relative_camera_position.xz().length() / radius,
524                        relative_camera_position.y / radius,
525                    );
526                    let azimuth = atan2(
527                        relative_camera_position.z * relative_camera_position.xz().length_recip(),
528                        relative_camera_position.x * relative_camera_position.xz().length_recip(),
529                    );
530
531                    commands
532                        .entity(camera_entity)
533                        .remove::<FreeCamera>()
534                        .insert(OrbitCamera {
535                            radius,
536                            inclination,
537                            azimuth,
538                        });
539                }
540            }
541
542            CameraMode::Free => {
543                for (camera_entity, _) in &cameras_query {
544                    commands
545                        .entity(camera_entity)
546                        .remove::<OrbitCamera>()
547                        .insert(FreeCamera::default());
548                }
549            }
550        }
551
552        any_changes = true;
553    }
554
555    if any_changes {
556        set_help_text(&app_status, &mut help_text_query);
557
558        // Reset the cursor grab mode, because the free camera controller may
559        // have enabled it, and we don't want the cursor to disappear.
560        for mut cursor_options in &mut windows_query {
561            cursor_options.grab_mode = CursorGrabMode::None;
562            cursor_options.visible = true;
563        }
564    }
565}
566
567/// A system that updates the radio buttons at the bottom of the screen to
568/// reflect whether gizmos are enabled or not.
569fn update_radio_buttons(
570    mut widgets_query: Query<(
571        Entity,
572        Option<&mut BackgroundColor>,
573        Has<Text>,
574        AnyOf<(
575            &WidgetClickSender<GizmosEnabled>,
576            &WidgetClickSender<ObjectToShow>,
577            &WidgetClickSender<CameraMode>,
578        )>,
579    )>,
580    app_status: Res<AppStatus>,
581    mut text_ui_writer: TextUiWriter,
582) {
583    for (
584        entity,
585        maybe_bg_color,
586        has_text,
587        (maybe_gizmos_enabled, maybe_object_to_show, maybe_camera_mode),
588    ) in &mut widgets_query
589    {
590        let selected = if let Some(sender) = maybe_gizmos_enabled {
591            app_status.gizmos_enabled == **sender
592        } else if let Some(sender) = maybe_object_to_show {
593            app_status.object_to_show == **sender
594        } else if let Some(sender) = maybe_camera_mode {
595            app_status.camera_mode == **sender
596        } else {
597            continue;
598        };
599
600        if let Some(mut bg_color) = maybe_bg_color {
601            widgets::update_ui_radio_button(&mut bg_color, selected);
602        }
603        if has_text {
604            widgets::update_ui_radio_button_text(entity, &mut text_ui_writer, selected);
605        }
606    }
607}
608
609/// Draws gizmos that show the boundaries of the various boxes associated with
610/// the light probes in the scene.
611fn draw_gizmos(
612    light_probes: Query<(&LightProbe, &ParallaxCorrection, &Transform)>,
613    app_status: Res<AppStatus>,
614    mut gizmos: Gizmos,
615) {
616    // If the user has gizmos disabled, bail.
617    if matches!(app_status.gizmos_enabled, GizmosEnabled::Off) {
618        return;
619    }
620
621    for (light_probe, parallax_correction, transform) in &light_probes {
622        // Draw light probe bounds.
623        gizmos.cube(*transform, TAN);
624
625        // Draw light probe falloff.
626        gizmos.cube(
627            Transform {
628                scale: transform.scale * (Vec3::ONE - light_probe.falloff),
629                ..*transform
630            },
631            CRIMSON,
632        );
633
634        // Draw light probe parallax correction bounds.
635        if let ParallaxCorrection::Custom(parallax_correction_bounds) = *parallax_correction {
636            gizmos.cube(
637                Transform {
638                    scale: transform.scale * parallax_correction_bounds,
639                    ..*transform
640                },
641                CORNFLOWER_BLUE,
642            );
643        }
644    }
645}
646
647/// Updates the help text at the top of the screen to reflect a change in camera
648/// or gizmo application settings.
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/3d/clearcoat.rs (line 331)
325    fn create_help_text(&self) -> Text {
326        let help_text = match *self {
327            LightMode::Point => "Press Space to switch to a directional light",
328            LightMode::Directional => "Press Space to switch to a point light",
329        };
330
331        Text::new(help_text)
332    }

Methods from Deref<Target = String>§

1.7.0 · Source

pub 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 · Source

pub 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 · Source

pub 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 · Source

pub 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 · Source

pub 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 · Source

pub 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 · Source

pub 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, "");
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: ❌❌✅");

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 Clone for Text

Source§

fn clone(&self) -> Text

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Component for Text
where Text: Send + Sync + 'static,

A component’s Required Components are inserted whenever it is inserted. Note that this will also insert the required components of the required components, recursively, in depth-first order.

Source§

const STORAGE_TYPE: StorageType = bevy_ecs::component::StorageType::Table

A constant indicating the storage type used for this component.
Source§

type Mutability = Mutable

A marker type to assist Bevy with determining if this component is mutable, or immutable. Mutable components will have Component<Mutability = Mutable>, while immutable components will instead have Component<Mutability = Immutable>. Read more
Source§

fn register_required_components( _requiree: ComponentId, required_components: &mut RequiredComponentsRegistrator<'_, '_>, )

Registers required components. Read more
Source§

fn clone_behavior() -> ComponentCloneBehavior

Called when registering this component, allowing to override clone function (or disable cloning altogether) for this component. Read more
Source§

fn relationship_accessor() -> Option<ComponentRelationshipAccessor<Text>>

Returns ComponentRelationshipAccessor required for working with relationships in dynamic contexts. Read more
Source§

fn on_add() -> Option<for<'w> fn(DeferredWorld<'w>, HookContext)>

Gets the on_add ComponentHook for this Component if one is defined.
Source§

fn on_insert() -> Option<for<'w> fn(DeferredWorld<'w>, HookContext)>

Gets the on_insert ComponentHook for this Component if one is defined.
Source§

fn on_discard() -> Option<for<'w> fn(DeferredWorld<'w>, HookContext)>

Gets the on_discard ComponentHook for this Component if one is defined.
Source§

fn on_remove() -> Option<for<'w> fn(DeferredWorld<'w>, HookContext)>

Gets the on_remove ComponentHook for this Component if one is defined.
Source§

fn on_despawn() -> Option<for<'w> fn(DeferredWorld<'w>, HookContext)>

Gets the on_despawn ComponentHook for this Component if one is defined.
Source§

fn map_entities<E>(_this: &mut Self, _mapper: &mut E)
where E: EntityMapper,

Maps the entities on this component using the given EntityMapper. This is used to remap entities in contexts like scenes and entity cloning. When deriving Component, this is populated by annotating fields containing entities with #[entities] Read more
Source§

impl Debug for Text

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
Source§

impl Default for Text

Source§

fn default() -> Text

Returns the “default value” for a type. Read more
Source§

impl Deref for Text

Source§

type Target = String

The resulting type after dereferencing.
Source§

fn deref(&self) -> &<Text as Deref>::Target

Dereferences the value.
Source§

impl DerefMut for Text

Source§

fn deref_mut(&mut self) -> &mut <Text as Deref>::Target

Mutably dereferences the value.
Source§

impl From<&str> for Text

Source§

fn from(value: &str) -> Text

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 FromArg for Text

Source§

type This<'from_arg> = Text

The type to convert into. Read more
Source§

fn from_arg(arg: Arg<'_>) -> Result<<Text as FromArg>::This<'_>, ArgError>

Creates an item from an argument. Read more
Source§

impl FromReflect for Text

Source§

fn from_reflect(reflect: &(dyn PartialReflect + 'static)) -> Option<Text>

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
Source§

impl GetOwnership for Text

Source§

fn ownership() -> Ownership

Returns the ownership of Self.
Source§

impl GetTypeRegistration for Text

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
Source§

impl IntoReturn for Text

Source§

fn into_return<'into_return>(self) -> Return<'into_return>
where Text: 'into_return,

Converts Self into a Return value.
Source§

impl PartialEq for Text

Source§

fn eq(&self, other: &Text) -> bool

Equality operator ==. Read more
1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Inequality operator !=. Read more
Source§

impl PartialReflect for Text

Source§

fn get_represented_type_info(&self) -> Option<&'static TypeInfo>

Returns the TypeInfo of the type represented by this value. 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<Text>) -> ReflectOwned

Returns an owned enumeration of “kinds” of type. Read more
Source§

fn try_into_reflect( self: Box<Text>, ) -> 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<Text>) -> 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_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 to_dynamic(&self) -> Box<dyn PartialReflect>

Converts this reflected value into its dynamic representation based on its kind. 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 reflect_hash(&self) -> Option<u64>

Returns a hash of the value (which includes the type). Read more
Source§

fn is_dynamic(&self) -> bool

Indicates whether or not this type is a dynamic type. Read more
Source§

impl Reflect for Text

Source§

fn into_any(self: Box<Text>) -> 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<Text>) -> 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 StructuralPartialEq for Text

Source§

impl TextSection for Text

Source§

fn get_text(&self) -> &str

Returns the text for this section.
Source§

fn get_text_mut(&mut self) -> &mut String

Returns a mutable reference to the text for this section.
Source§

impl TupleStruct for Text

Source§

fn field(&self, index: usize) -> Option<&(dyn PartialReflect + 'static)>

Returns a reference to the value of the field with index index as a &dyn Reflect.
Source§

fn field_mut( &mut self, index: usize, ) -> Option<&mut (dyn PartialReflect + 'static)>

Returns a mutable reference to the value of the field with index index as a &mut dyn Reflect.
Source§

fn field_len(&self) -> usize

Returns the number of fields in the tuple struct.
Source§

fn iter_fields(&self) -> TupleStructFieldIter<'_>

Returns an iterator over the values of the tuple struct’s fields.
Source§

fn to_dynamic_tuple_struct(&self) -> DynamicTupleStruct

Creates a new DynamicTupleStruct from this tuple struct.
Source§

fn get_represented_tuple_struct_info(&self) -> Option<&'static TupleStructInfo>

Will return None if TypeInfo is not available.
Source§

impl TypePath for Text

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 Text

Source§

fn type_info() -> &'static TypeInfo

Returns the compile-time info for the underlying type.

Auto Trait Implementations§

§

impl Freeze for Text

§

impl RefUnwindSafe for Text

§

impl Send for Text

§

impl Sync for Text

§

impl Unpin for Text

§

impl UnsafeUnpin for Text

§

impl UnwindSafe for Text

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<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<C> Bundle for C
where C: Component,

Source§

fn component_ids( components: &mut ComponentsRegistrator<'_>, ) -> impl Iterator<Item = ComponentId> + use<C>

Source§

fn get_component_ids( components: &Components, ) -> impl Iterator<Item = Option<ComponentId>>

Return a iterator over this Bundle’s component ids. This will be None if the component has not been registered.
Source§

impl<C> BundleFromComponents for C
where C: Component,

Source§

unsafe fn from_components<T, F>(ctx: &mut T, func: &mut F) -> C
where F: for<'a> FnMut(&'a mut T) -> OwningPtr<'a>, C: Sized,

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> 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<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> 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<C> DynamicBundle for C
where C: Component,

Source§

type Effect = ()

An operation on the entity that happens after inserting this bundle.
Source§

unsafe fn get_components( ptr: MovingPtr<'_, C>, func: &mut impl FnMut(StorageType, OwningPtr<'_>), ) -> <C as DynamicBundle>::Effect

Moves the components out of the bundle. Read more
Source§

unsafe fn apply_effect( _ptr: MovingPtr<'_, MaybeUninit<C>>, _entity: &mut EntityWorldMut<'_>, )

Applies the after-effects of spawning this bundle. Read more
Source§

impl<T> DynamicTypePath for T
where T: TypePath,

Source§

impl<T> DynamicTyped for T
where T: Typed,

Source§

impl<T> ErasedBundleTemplate for T
where T: Template + Send + Sync + 'static, <T as Template>::Output: Bundle,

Source§

unsafe fn apply( &self, context: &mut TemplateContext<'_, '_>, ) -> Result<(), BevyError>

Applies this template to the given entity. Read more
Source§

fn clone_template(&self) -> Box<dyn ErasedBundleTemplate>

Clones this template. See Clone.
Source§

impl<T> ErasedComponentTemplate for T
where T: Template + Send + Sync + 'static, <T as Template>::Output: Component,

Source§

unsafe fn apply( &self, context: &mut TemplateContext<'_, '_>, bundle_writer: &mut BundleWriter<'_>, ) -> Result<(), BevyError>

Applies this template to the given entity. Read more
Source§

fn clone_template(&self) -> Box<dyn ErasedComponentTemplate>

Clones this template. See Clone.
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<S> GetTupleStructField for S
where S: TupleStruct,

Source§

fn get_field<T>(&self, index: usize) -> Option<&T>
where T: Reflect,

Returns a reference to the value of the field with index index, downcast to T.
Source§

fn get_field_mut<T>(&mut self, index: usize) -> Option<&mut T>
where T: Reflect,

Returns a mutable reference to the value of the field with index index, downcast to T.
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<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> 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<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> 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> 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