#my cat version called dog plz critique

23 messages · Page 1 of 1 (latest)

untold canyon
#

Tried to write idiomatic rust. hard to shake off being for-loop-brained.

use std::fs;
use std::process;
use std::error::Error;
use clap::Parser;

#[derive(Parser)]
struct Args {
    file_path: std::path::PathBuf,
    #[arg(short = 'n', long)]
    line_numbers: bool,
}

fn get_lines(args: &Args) -> Result<Vec<String>, Box<dyn Error>> {
    let contents = fs::read_to_string(&args.file_path)?;
    let results = if args.line_numbers {
        contents
            .lines()
            .enumerate()
            .map(|(i, line)| format!("{:>6}\t{line}", i+1))
            .collect()
    } else {
        contents
            .lines()
            .map(|line| format!("{line}"))
            .collect()
    };

    Ok(results)
}

fn main() {
    let args = Args::parse();

    let results = get_lines(&args);

    let _ = match results {
        Ok(lines) => {
            for line in lines {
                println!("{line}");
            }
        },
        Err(e) => {
            eprintln!("An error occured: {e}");
            process::exit(1);
        }
    };
}
#
   Compiling dog v0.1.0 (/home/shurjo/learning/dog)
    Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.14s
     Running `target/debug/dog -n poem.txt`
     1    I'm nobody! Who are you?
     2    Are you nobody, too?
     3    Then there's a pair of us - don't tell!
     4    They'd banish us, you know.
     5    
     6    How dreary to be somebody!
     7    How public, like a frog
     8    To tell your name the livelong day
     9    To an admiring bog!
    10    
#

works fine

vestal ivy
#

its still ok

#

sometimes iterators

#

sometimes for loops

#

dont gotta use for loops for everything

#

dont gotta use iterators for everything

desert jacinth
#

what's the let _ = for? I don't think you need that.
I'd personally prefer to change the return type of the main function over using exit, e.g., fn main() -> Result<(), Box<dyn Error>>.
Otherwise the code seems fine to me :)

vestal ivy
#

?eval

use std::{fs, io};
use std::path::PathBuf;
use clap::Parser;

#[derive(Parser)]
struct Args {
    file_path: PathBuf,
    #[arg(short = 'n', long)]
    line_numbers: bool,
}

fn get_lines(args: &Args) -> io::Result<Vec<String>> {
    let contents = fs::read_to_string(&args.file_path)?;
    let results = if args.line_numbers {
        contents
            .lines()
            .enumerate()
            .map(|(i, line)| format!("{:>6}\t{line}", i + 1))
            .collect()
    } else {
        contents
            .lines()
            .map(|line| line.to_string())
            .collect()
    };

    Ok(results)
}

fn main() {
    let args = Args::parse();

    let results = get_lines(&args).unwrap();

    for line in results {
        println!("{line}");
    }
}
#

what i would write kinda

crystal gateBOT
#
error: the following required arguments were not provided:
  <FILE_PATH>

Usage: playground <FILE_PATH>

For more information, try '--help'.
desert jacinth
#

I'd return the error from main rather than unwrapping

untold canyon
# vestal ivy its still ok

but aren’t iterators more efficient? not trying to prematurely optimize but it’s kinda what i see everyone doing for everything

vestal ivy
#

if you do .collect its prob an iterator thing

#

but like if your thing ends with .for_each you can do a for loop

#

like

#

?godbolt

#[unsafe(no_mangle)]
fn triangle_for(x: usize) -> usize {
    let mut out = 0;
    for i in 0..x {
        out += i;
    }
    out
}

#[unsafe(no_mangle)]
fn triangle_iter(x: usize) -> usize {
    (0..x).sum()
}
crystal gateBOT
#
triangle_for:
        test    rdi, rdi
        je      .LBB0_1
        lea     rax, [rdi - 1]
        lea     rcx, [rdi - 2]
        mul     rcx
        shld    rdx, rax, 63
        lea     rax, [rdi + rdx]
        dec     rax
        ret
.LBB0_1:
        xor     eax, eax
        ret

triangle_iter:
        test    rdi, rdi
        je      .LBB1_1
        lea     rax, [rdi - 1]
        lea     rcx, [rdi - 2]
        mul     rcx
        shld    rdx, rax, 63
        lea     rax, [rdi + rdx]
        dec     rax
        ret
.LBB1_1:
        xor     eax, eax
        ret
```Note: only `pub fn` at file scope are shown
untold canyon
#

word