[spam] language learning: rust

Undiscussed Horrific Abuse, One Victim of Many gmkarl at gmail.com
Sun Apr 24 01:59:13 PDT 2022


https://doc.rust-lang.org/book/

rustup doc --book # https://github.com/rust-lang/rustup/issues/2980

Notes:

1 getting started

cargo is optional for using rust. it provides for reproducible builds from
versioned dependencies using Cargo.lock .

hello_cargo: # or write the other two files by hand
cargo new hello_cargo
cd hello_cargo

Cargo.toml:
[package]
name = "hello_cargo"
version = "0.1.0"
edition = "2021"

[dependencies]

src/main.rs:
fn main() {
    println!("Hello, world!");
}

rustc src/main.rs # compile by hand
cargo check # verify syntax
cargo build # compile with cargo
cargo run # executes target/debug/hello_cargo

cargo run will automatically build
cargo build will automatically
pass --release to build to target/release

Most rust projects out there will build with "cargo build".

2 guessing game

src/main.rs:
use std::io;

fn main() {
    println!("Guess the number!");

    println!("Please input your guess.");

    let mut guess = String::new();

    io::stdin()
        .read_line(&mut guess)
        .expect("Failed to read line");

    println!("You guessed: {}", guess);
}

global things like println! and String are listed at
https://doc.rust-lang.org/std/prelude/index.html

std::io provides io::stdin and its read_line member locally. These are
always accessible globally with std::io::stdin.

constants and mutables:
let apples = 5; // immutable
let mut bananas = 5; // mutable

String::new is a static or associated function of the string type. It
creates a new String.

in read_line(&mut guess), & specifies to pass guess by reference rather
than value, and mut specifies to let read_line mutate it

functions in rust often return Results, enums of either Ok or Err that can
have type members and associated data. io::Result has a .expect member
function that either raises the passed error text for Err, or returns the
associated data for Ok.

rust emits warnings for unhandled Results.

Cargo.toml:
[package]
name = "guessing_game"
version = "0.1.0"
edition = "2021"

# See more keys and their definitions at
https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
rand = "0.8.3"

diff -u main.rs.old main.rs:
--- main.rs.old 2022-04-24 04:40:47.371994619 -0400
+++ main.rs     2022-04-24 04:40:01.011994637 -0400
@@ -1,8 +1,13 @@
 use std::io;
+use rand::Rng;

 fn main() {
     println!("Guess the number!");

+    let secret_number = rand::thread_rng().gen_range(1..101);
+
+    println!("The secret number is: {}", secret_number);
+
     println!("Please input your guess.");

     let mut guess = String::new();

rand::Rng adds random number generator traits. without it, gen_range() does
not appear on thread_rng().

rand::thread_rng() is a thread local OS-seeded prng.

1..101 is a range expression of [1,101). it is equivalent here to 1..100
which is [1,100].

cargo doc --open will show documentation of the rand and all other project
crates.

use rand::Rng;
use std::cmp::Ordering;
use std::io;

fn main() {
    println!("Guess the number!");

    let secret_number = rand::thread_rng().gen_range(1..101);

    loop {
        println!("Please input your guess.");

        let mut guess = String::new();

        io::stdin()
            .read_line(&mut guess)
            .expect("Failed to read line");

        let guess: u32 = match guess.trim().parse() {
            Ok(num) => num,
            Err(_) => continue,
        };

        println!("You guessed: {}", guess);

        match guess.cmp(&secret_number) {
            Ordering::Less => println!("Too small!"),
            Ordering::Greater => println!("Too big!"),
            Ordering::Equal => {
                println!("You win!");
                break;
            }
        }
    }
}


rust lets you shadow variables in the same scope, retyping them, optionally
based on their previous values

String::trim removes the enter character read_line preserved
String::parse returns a number

match {} is a switch or select statement that provides for patterns and use
as an expression

rust infers the type of secret_number from the type of guess

std::cmp::Ordering is an enum type return by the .cmp method.

Homework:
1. Implement and run the guessing example.
2. Make a rust project that uses std::io to generate a .jl julia script
that performs and outputs the result of an arithmetic calculation.

file output: https://doc.rust-lang.org/stable/std/io/
julia: see other thread with similar name
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: text/html
Size: 9161 bytes
Desc: not available
URL: <https://lists.cpunks.org/pipermail/cypherpunks/attachments/20220424/3b1bc443/attachment.txt>


More information about the cypherpunks mailing list