Rust cheatsheet
Husk at der kan søges efter hjælp til Rust på nettet ved at søge på rust <beskrivelse> fx rust assign variable.
Mere uddybende Rust cheatsheet.
Variabler
let a_variable = 5;
let mut a_mutable_variable = 10;Funktioner
fn a_function(){
println!("hi")
}fn function_with_parameter_and_return_value(x: i8) -> i8 {
return x.pow(2)
}Kommentarer
// Kommentar på en linje
/*
Kommentar
over flere
linjer
*/Betingelser
if condition {
println!("if condition is true")
} else if condition2{
println!("else if condition2 is true")
} else {
println!("otherwise")
}if something == something_else {
println!("== is used for comparion. Not equal: !=")
}
if condition && condition2 {
println!("both true")
}
if condition || condition2 {
println!("one or both are true")
}
if !condition {
println!("not condition")
}Løkker
for k in [2,3,4]{
println!("{k}")
}
for k in 0..5 {
println!("{k}")
}
while condition {
println!("while condition is true")
}
loop {
println!("infinite loop")
}Datastrukturer
let a_str = "hi";
let a_string = String::from("hi");
let an_array = [2,5,8];
let a_vector = vec![2,5,8];
let a_tuple = (2,5,8);use std::collections::HashMap;
let a_hashmap = HashMap::from([("Mercury", 0.4),("Venus", 0.7)]);Struct
struct MyStruct {
x: i8
}
let a_variable = MyStruct{x:5};
println!("{}",a_variable.x)Læse fra fil
Se std::fs::read_to_string samt evt. str metoderne split og parse.
use std::fs;
fn main() {
let contents = fs::read_to_string("example.txt").expect("Kunne ikke læse fil.");
let mut numbers: Vec<f32> = Vec::new();
for line in contents.split("\n"){
numbers.push(line.trim().parse().expect("Der antages nøjagtigt et tal per linje!"));
}
println!("{:?}",numbers);
}Til struktureret data findes crates fx: serde, csv.
Mere effektivt kan der undlades at gemme alle tekststrenge i hukommelsen under indlæsning som i eksemplet nedenfor.
use std::fs::File;
use std::io::{self, BufRead};
fn main() {
let file = File::open("example.txt").expect("Kunne ikke læse fil.");
let lines = io::BufReader::new(file).lines();
for line in lines {
println!("{:?}", line.expect("Kunne ikke læse linje."));
}
}