Quantcast
Channel: General Programming - MetaRuby - Ruby Forum
Viewing all articles
Browse latest Browse all 46

Getting started in Rust

$
0
0

@danielpclark wrote:

I'm starting to learn Rust! This would make an excellent place to learn it! This is my first "program". All it does is take user input, matches all the integers via regex. Converts the strings to integers, multiply them by 2, and append them on a vector. Then print out the results.

Here's the dependency

[dependencies]
regex = "0.1.41"

And the script

extern crate regex;

use std::io;
use regex::Regex;

fn main() {
  println!("It's Rust!");

  let mut guess = String::new();

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

  let re = Regex::new(r"(\d+)").unwrap();

  let mut results: Vec<i32> = vec![];

  for cap in re.captures_iter(&guess) {
    let mut val: i32 = cap.at(0).unwrap().parse::<i32>().unwrap();
    val *= 2;
    results.push(val)
  };
  
  println!("{:?}", results);
}

My thoughts/discoveries during the process

I used Regex because converting a String to an Array looked like it would be very difficult to figure out. I used a Vector for the new Array because it's not a fixed size and I can used an undetermined amount of input for it. One thing I found is that when you have a method return a result you get an object wrapper of a result (I believe this to be true, I could be wrong), and each item you return you need to unwrap() to get the raw type result. Parameters preceded with an ampersand are "borrowed" references (as in - they don't take ownership of the object/memory).

Example output (and input)

It's Rust!
3,4,5
[6, 8, 10]

Getting started

Install Rust. Use cargo new project_name --bin to generate a program directory. Add any dependencies in the .toml file. And edit the src/main.rs with your code. When you're ready run cargo build, and if you have no errors then run cargo run. If you do see errors you will have a very detailed explanation of what's wrong.

To get a good idea of how Rust works watch this presentation:

Posts: 12

Participants: 3

Read full topic


Viewing all articles
Browse latest Browse all 46

Trending Articles