乐闻世界logo
搜索文章和话题

How do you work with standard string types in Rust?

1个答案

1

In Rust, the standard string types are String and string slices &str. String is a growable, mutable, and owned UTF-8 string type, while &str is typically used as a string borrow, which is a slice pointing to a valid UTF-8 sequence and is immutable.

Creating String

To create a new String in Rust, you can use String::new() to create an empty string, or String::from("specified content") to create a string initialized with content.

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

Updating String

String can be modified in various ways. For example, you can use push_str() to append a string slice or push() to add a single character.

rust
s.push_str(", world!"); s.push('!');

Using String and &str

When you want to obtain an immutable reference to a String, you can use the & operator. This creates a &str reference from the String.

rust
let s_slice: &str = &s;

Example: Function Handling Strings

Here is a simple example function that demonstrates how to receive a string slice as a parameter and return a String:

rust
fn greet(name: &str) -> String { format!("Hello, {}!", name) } let greeting = greet("Alice"); println!("{}", greeting); // Output: Hello, Alice!

Strings and Error Handling

When handling strings, especially when dealing with external data, errors may occur. For example, attempting to create a string from invalid byte sequences will result in runtime errors. In such cases, it is better to use String::from_utf8 for handling potential errors.

rust
let bytes = vec![0x48, 0x65, 0x6C, 0x6C, 0x6F]; // "Hello" UTF-8 bytes let s = String::from_utf8(bytes); match s { Ok(valid_string) => println!("Converted string: {}", valid_string), Err(e) => println!("Failed to convert: {}", e), }

Through these examples, you can see the basic methods and common use cases for handling String and &str in Rust.

2024年8月7日 14:21 回复

你的答案