Rust features
Features of the language
connect some &str variables
Best way
Use to_string()
let str1 = "Hello, ";
let str2 = "world!";
let result_string = str1.to_string() + str2;
to_owned()
Creates owned data from borrowed data, usually by cloning.
let s: &str = "a";
let ss: String = s.to_owned();
let v: &[i32] = &[1, 2];
let vv: Vec<i32> = v.to_owned();
Trait bound, Lifetime bound
Trait bound: limitation of implementing type
is a subset of ( は の部分集合)
(I'm apologize for suddenly writting in Japanese :<)
pub fn spawn<F, T>(f: F) -> JoinHandle<T>
where
F: FnOnce() -> T,
F: Send + 'static,
T: Send + 'static,
type alias
You can define the type alias shorter than that of defining directory.
type Job = Box<dyn FnOnce() + Send + 'static>
Pattern Matching
Option
Official says
Type Option represents an optional value: every Option is either Some and contains a value, or None, and does not. Option types are very common in Rust code, as they have a number of uses:
- Initial values
- Return values for functions that are not defined over their entire input range (partial functions)
- Return value for otherwise reporting simple errors, where None is returned on error
- Optional struct fields
- Struct fields that can be loaned or “taken”
- Optional function arguments
- Nullable pointers
- Swapping things out of difficult situations
If the type of the return value is Option
, when expanding, it will be Some
or None
Result
Official says
Result<T, E> is the type used for returning and propagating errors. It is an enum with the variants, Ok(T), representing success and containing a value, and Err(E), representing error and containing an error value.
enum Result<T, E> {
Ok(T),
Err(E),
}
take() method
This method on Option
takes the Some
variant out and leaves None
in its place.
if let Some(thread) = worker.thread.take() {
thread.join().unwrap();
}
Preallocate size of vec
Vec::with_capacity()
is similar to Vec::new()
. But They have a little bit difference.
The vec declared by with_capacity()
doesn't grow infinity.
`?` keyword
In Rust, the ?
symbol is used in the context of error handling. It is often referred to as the "question mark operator" or "try operator." The ?
is used to simplify the propagation of errors in a concise and ergonomic manner.
When a function returns a Result
or Option
, and you want to propagate the error or unwrap the value, you can use the ?
operator. If the result is an Err
or None
, the function will return early with the error, otherwise, it will continue executing.
use std::fs::File;
use std::io::{self, Read};
fn read_file_contents(file_path: &str) -> Result<String, io::Error> {
// Attempt to open the file
let mut file = File::open(file_path)?;
// Read the contents of the file
let mut contents = String::new();
file.read_to_string(&mut contents)?;
Ok(contents)
}
fn main() {
match read_file_contents("example.txt") {
Ok(contents) => println!("File contents: {}", contents),
Err(err) => eprintln!("Error reading file: {}", err),
}
}
# Crate
binary crate
- Binary crate has main()
function in the file (commonly main.rs
).
- It works on standalone.
## library crate
- Library crate doesn't have main
function.
- It doesn't work standalone. And it is imported to use.
- By writting some libraries in Cargo.toml
, you can use them.
# System commands
## cargo check
Execute dry-run the binary crate in the project.
## cargo doc --open
Make a documataion file
to target/doc
.
If you append the open
argument, you can the doc being made would open.
コメント