Learning-Rust.Github.io: Rust Programming Language Tutorials for Everyone
Rust Illuminated. Grasp Quickly. Rust Programming Language Tutorials for Everyone! Data and behavior struct Person { name: String, company_name: String, } impl Person { fn new(name: String, company_name: String) -> Self { Self { name, company_name } } fn intro(&self) -> String { format!("I'm {} from {}", self.name, self.company_name) } } trait Greet { const PREFIX: &'static str = "Hello"; fn greet(&self) -> String { format!("{}!", String::from(Self::PREFIX)) } } impl Greet for Person {} fn main() { let steve = Person::new("Steve".to_string(), "Apple".to_string()); println!("{}", steve.greet()); // Hello! println!("{}", steve.intro()); // I'm Steve from Apple } Functional fn main() { let marks = ["10", "20", "30", "0.4", "0.5", "invalid"]; let sum: i32 = marks // Iterate through marks .iter() // Parse string to float, ignore if invalid .filter_map(|&s| s.parse::<f64>().ok()) // Multiply decimals under 1.0 by 100 .map(|num| if num < 1.0 { num * 100.0 } else { num }) // Trace the values .inspect(|&val| println!("Parsed: {val}")) // Cast float to integer .map(|num| num as i32) // Aggregate .sum(); println!("Final: {sum}"); // 150 } Advanced blueprint use std::collections::HashMap; enum Data<K, V> { Value(V), KeyValue(K, V), } fn main() { let data = vec![ Data::KeyValue("Steve", 10), Data::Value(20), Data::KeyValue("Bill", 30), Data::Value(40), ]; let map = data .into_iter() // Pattern matching and destructuring .map(|item| match item { Data::KeyValue(k, v) => { println!("{k}: {v}"); (k.to_string(), v) } Data::Value(v) => { println!("unknown: {v}"); ("unknown".to_string(), v) } }) // Accumulate items into a map .fold(HashMap::new(), |mut map, (key, value)| { map.entry(key) .and_modify(|existing| *existing += value) .or_insert(value); map }); println!("Map: {:?}", map); // Map: {"unknown": 60, "Bill": 30, "Steve": 10} } The world’s fastest framework for building websites. Fully static search library that aims to perform well on large sites. Modern & modular technical documentation and blog setup. Help us to improve the documentation.