Skip to content

Instantly share code, notes, and snippets.

@pmcgee69
Last active October 9, 2024 20:12
Show Gist options
  • Save pmcgee69/3f82cba764964d505166a35596351423 to your computer and use it in GitHub Desktop.
Save pmcgee69/3f82cba764964d505166a35596351423 to your computer and use it in GitHub Desktop.
Rust examples that are familiar to Object Pascal programmers
// Source: Hands-on Rust.
use​ ​std​::​io​::stdin;
fn​ ​main() {
letMYLIST = [ ​"One"​, ​"Two"​, ​"Three"​ ];
​  ​for​ i in 0..3 {
​  println!(​"{}"​, MYLIST[i]);
​  }
}
fn​ ​main1​() {
let​ my_list = [ ​"One"​, ​"Two"​, ​"Three"​ ];
​  for​ num in &my_list {
​  println!(​"{}"​, num);
​  }
}
​fn​ ​main2​() {
​ println!(​"Hello, what's your name?"​);
​ let​ ​mut​ your_name = ​String​::​new​();
​ stdin​()
​ ​.read_line​(&​mut​ your_name)
​ ​.expect​(​"Failed to read line"​);
​ your_name
​ ​.trim​()
​ ​.to_lowercase​()
​ println!(​"Hello, {}"​, your_name)
​}
​struct​ Visitor {
​ name: String,
​ greeting: String,
​}
impl​ Visitor {
​fn​ ​new​(name: &str, greeting: &str) ​->​ Self {
Self {
name: name​.to_lowercase​(),
greeting: greeting​.to_string​(),
}
}
}
fn​ ​greet_visitor​(&​self​) {
​ println!(​"{}"​, ​self​.greeting);
​ }
​}
let​ visitor_list = [
​ Visitor​::​new​(​"bert"​ , ​"Hello Bert, enjoy your treehouse."​),
​ Visitor​::​new​(​"steve"​, ​"Hi Steve. Your milk is in the fridge."​),
​ Visitor​::​new​(​"fred"​ , ​"Wow, who invited Fred?"​),
];
let​ known_visitor = visitor_list
​​ ​.iter​()
​​ ​.find​(|visitor| visitor.name == name);
fn​ ​check_visitor_name​(visitor: &Visitor, name: &String) ​->​ bool {
​ ​return​ visitor.name == name;
​}
​match​ known_visitor {
​​​ ​Some​(visitor) ​=>​ visitor​.greet_visitor​(),
​​​ None ​ =>​ println!(​"You are not on the visitor list. Please leave."​)
}
​let​ ​mut​ visitor_list2 = vec! [
​ ​ Visitor​::​new​(​"Bert"​, ​"Hello Bert, enjoy your treehouse."​),
​ ​ Visitor​::​new​(​"Steve"​, ​"Hi Steve. Your milk is in the fridge."​),
​ ​ Visitor​::​new​(​"Fred"​, ​"Wow, who invited Fred?"​),
​ ];
​match​ known_visitor {
​ Some​(visitor) ​=>​ visitor​.greet_visitor​(),
​ None ​=>​ {
​​​ ​if​ name​.is_empty​() {
​​​ ​break​;
​ } ​else​ {
​ println!(​"{} is not on the visitor list."​, name);
visitor_list2​.push​(​Visitor​::​new​(&name, ​"New friend"​));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment