Menu
CoddyTech

Strings and UTF-8

Lesson 21 of 48 in Coddy's Rust for Go Developers course.

Go strings are immutable byte sequences and may contain invalid UTF-8; ranging over a Go string decodes runes and reports replacement runes for invalid sequences. Rust String and str always contain valid UTF-8. Bytes, Unicode scalar values, and visible grapheme clusters are different units.

Rust does not allow integer indexing of str to guess a character. Use chars() for scalar iteration or as_bytes() for bytes. A byte range used to slice text must start and end at UTF-8 boundaries. Reversing scalar values below is valid UTF-8 but is not a general grapheme-aware text reversal.

Complete Go comparison program:

package main
import "fmt"
func main() {
    runes := []rune("a猫")
    for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 { runes[i], runes[j] = runes[j], runes[i] }
    fmt.Println(string(runes))
}

Go output:

猫a

Complete Rust teaching program:

fn main() {
    let reversed: String = "a猫".chars().rev().collect();
    println!("{}", reversed);
}

Rust output:

猫a
challenge icon

Challenge

Easy

Implement pub fn redact(text: &str, needle: char) -> String and pub fn measure(text: &str) -> (usize, usize) in textwork.rs. Redact replaces each Unicode scalar exactly equal to needle with one ASCII *, preserving all other scalars in order. Measure returns (bytes, scalars), not grapheme clusters. Input is one needle character on the first line and text on the second. solve returns bytes:scalars|redacted, measuring the original text. Empty text is valid; matching is case-sensitive. No embedded newline appears in the text.

Implement the required exported APIs and return the result from exercise::solve(input: &str) -> String without a final newline. Do not print in editable code. The locked driver checks required APIs independently, reads all stdin, and prints the returned text with one final newline.

Your code goes in exercise.rs, textwork.rs. main.rs holds the supplied input/output code and cannot be edited.

Try it yourself

#![allow(dead_code, unused_imports, unused_variables, unused_mut)]
mod exercise;
mod textwork;
use std::io::{self, Read};
fn main() {
    let mut input=String::new();
    io::stdin().read_to_string(&mut input).unwrap();
    // BEGIN PUBLIC API PROBES
assert_eq!(textwork::redact("λaλλ!", 'λ'), "*a**!");
assert_eq!(textwork::measure("λaλλ!"), (8, 5));
assert_eq!(textwork::measure("e\u{301}"), (3, 2));
assert_eq!(textwork::redact("", 'x'), "");
assert_eq!(textwork::measure(""), (0, 0));
assert_eq!(textwork::redact("AbA", 'a'), "AbA");

    // END PUBLIC API PROBES
    println!("{}", exercise::solve(&input));
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Rust for Go Developers

Practice on your own: Online Rust compiler