HexLibraryHexLibrary
</> HexCodeSign inSign up
PythonJavaScriptTypeScriptCC++JavaPHPGoRustRubyBashSQLLuaPerlCOBOLPascalDelphiFortranDartSwiftC#JuliaGroovyRElixirHaskellKotlinScalaClassic ASPClipperMS-DOS
LESSONS
Introduction to RustVariablesData TypesOperatorsStringsVectors (Vec)Conditions (if / match)Loops (for / while)FunctionsOwnership & Borrowing
REFERENCE
📖 Overview
🖥️ Output
📦 Variables
🔢 Numbers & Math
✍️ String
📋 Vector & HashMap
🔁 Condition & Loop
🧩 Function
🔑 Ownership & Borrowing
Rust›Strings

Strings

&str and String, length, uppercase (to_uppercase), and concatenation.

Simple enough for a 5-year-old to understand

Create a String and get its length

String literals are &str; String is used for growable text.

Example code
1
fn main() {
2
let mut s = String::from("Hex");
Owned, mutable text.
VariableOwned, mutable text.
3
s.push_str("Library");
Append to the end.
CodeAppend to the end.
4
println!("{} {}", s, s.len());
HexLibrary 10
Output / InputHexLibrary 10
5
}
VariableCodeOutput / Input

🎯 Exercise & Practice

Test what you've learned — answer, write code, check instantly. (1 left)

1.Print the text "hexlibrary" in UPPERCASE.

🎯 Expected output: HEXLIBRARY

Loading editor…

About this topic

There are two types for strings in Rust, and this is where beginners get stuck the most. String is an owned and growable string; the slice type is a borrowed view of an existing string and its size is immutable.

The reason for the distinction is ownership. String literals you write into the code reside inside the executable file and cannot be modified; they are accessed as slices. Strings created and grown at runtime are of type String and manage their own memory.

Rust stores strings as UTF-8 and enforces this. Therefore, accessing a string by index is FORBIDDEN: a byte might not be a letter. chars is used to iterate letter by letter, and bytes is used byte by byte — you explicitly state which one you want.

What you will learn

  • The difference between String and slice types
  • Why accessing strings by index is forbidden
  • Adding text with push_str
  • Iterating over characters with chars
  • Converting between string and number

When to use?

Use the slice type in function parameters: it accepts both String and string literals and does not make copies. Requesting a String parameter forces the caller to give up ownership.

Use String if you will grow the text or move its ownership; a slice is sufficient if you are only going to read it.

Common mistakes

Wrong

fn main() {
    let text = String::from("hello");
    println!("{}", text[0]);
}

Strings cannot be accessed by index in Rust; the compiler gives "the type str cannot be indexed by usize" error. The reason is UTF-8: a byte might not be a letter, and returning a single byte would produce a corrupted character. The chars iterator is used for the first character.

Correct

fn main() {
    let text = String::from("hello");
    if let Some(first) = text.chars().next() {
        println!("{}", first);
    }
}

Wrong

fn main() {
    let mut text = String::from("Hel");
    text = text + "lo";
    text.push_str("!");
    println!("{}", text);
}

This code compiles, but the plus operator takes OWNERSHIP of the left operand and produces a new String; when used in a loop, it reallocates at every step. Using push_str to append text is both more explicit and more efficient.

Correct

fn main() {
    let mut text = String::from("Hel");
    text.push_str("lo");
    text.push_str("!");
    println!("{}", text);
}

Wrong

fn main() {
    let input = "42";
    let number: i32 = input.parse();
    println!("{}", number + 1);
}

parse returns a Result type, not a direct number; because the conversion can fail. The compiler gives "expected i32, found Result" error. Rust puts the possibility of error into the type system, so you cannot skip the check.

Correct

fn main() {
    let input = "42";
    match input.parse::<i32>() {
        Ok(number) => println!("{}", number + 1),
        Err(_) => println!("Invalid number"),
    }
}

Frequently asked questions

Which one should I use in function parameters?

Almost always the slice type. The slice accepts both String and string literals, does not make copies, and does not force the caller to give up ownership. A String parameter is only needed if the function will store the value.

Why doesn't len give the number of letters?

Because it gives the number of BYTES. Since Turkish characters take two bytes in UTF-8, len comes out greater than the number of letters. To count letters, you need to get the count of elements from the chars iterator, and this operation scans the text from start to finish.

Why can't I convert text directly to a number?

You can convert it, but the result comes as a type that carries the possibility of failure. Rust does not hide the possibility of an error; the fact that the conversion might fail is visible in the type system and you cannot skip the check. This is the design that prevents runtime crashes.

Summary

String is owned and growable; the slice type is a borrowed read-only view.

Strings cannot be accessed by index because a byte might not be a letter.

chars is used to iterate over characters, and bytes is used for bytes.

parse returns a Result type; success checking cannot be skipped.

HexLibraryHexLibrary

Learn programming more clearly. Every command is explained line by line with colors, reinforced with runnable exercises, test your code instantly — all in one place, free.

Learn

  • Home
  • Languages & Lessons
  • HexCode

Company

  • About
  • Contact

Legal

  • Privacy Policy
  • Terms of Use

Other Projects

  • HexToolz
  • Free Service Manuals
© 2026 HexLibrary · The clearest way to learn code