← All Exercises

Rust String Slices

basicrust~15min

Background

String slices are views into string data, enabling zero-copy substring operations in Rust.

Problem

Write a Rust function that takes a string slice and returns the first word (up to the first space) as a string slice.

Input

A string slice (&str) containing words separated by spaces.

Output

A string slice of the first word, or an empty slice if no space is found.

Sample tests

Sample 1

Input: "hello world"
Expected: "hello"

Your solution

Learning objective

Learn string slices, lifetime elision, and zero-copy substring extraction.