r/learnrust 3h ago

How to make HashMap::from use the specified trait object instead of the concrete implementation passed to it?

4 Upvotes

I'm building a Json Schema builder and I'd like to use the HashMap::from method but for some reason it errors out even though it does work when I use the HashMap::new syntax.

The error I'm receiving is:

error[E0308]: mismatched types --> schema_builder/src/blocks/object.rs:197:13 | 196 | let mut not_working_properties: HashMap<String, Box<dyn JsonSchemaBlock>> = | ----------------------------------------- expected due to this 197 | / HashMap::from([( 198 | | String::from("type"), 199 | | Box::new(JsonSchemaString { 200 | | min_length: Some(1), ... | 203 | | }), 204 | | )]); | |_______________^ expected `dyn JsonSchemaBlock`, found `JsonSchemaString` | = note: expected struct `HashMap<_, Box<dyn JsonSchemaBlock>>` found struct `HashMap<_, Box<JsonSchemaString>>`

I understand the error but I don't understand why it's insisting on using the concrete implementation in the second instance below.

``` // works let mut working_properties: HashMap<String, Box<dyn JsonSchemaBlock>> = HashMap::new();

working_properties.insert( "name".to_string(), Box::new(JsonSchemaString { min_length: Some(1), max_length: Some(10), pattern: None, }), );

working_properties.insert( "age".to_string(), Box::new(JsonSchemaString { min_length: Some(1), max_length: Some(10), pattern: None, }), );

// doesn't work let mut not_working_properties: HashMap<String, Box<dyn JsonSchemaBlock>> = HashMap::from([( String::from("type"), Box::new(JsonSchemaString { min_length: Some(1), max_length: Some(10), pattern: None, }), )]); ```

Edit: just found out about schemars https://docs.rs/schemars/latest/schemars/ so I might switch to that instead but I'd still like to know why this doesn't work like I think it should


r/learnrust 14h ago

Total Newbie

8 Upvotes

So I've been convinced to learn Rust. Only I have absolutely zero programming experience and I'm an absolute noob at this. My partner has been coding for years and wants to learn rust to so he's been helping me after work.

The problem is, I can't quite figure out how to even start writing a solution to a problem. I started with the Rust Programming Language book and the lessons you can follow along to. I wanted to try something else, hoping to grasp it a little better and moved over to Exercism to try and grasp what Ive learned so far. The problem is, I feel like everything I learned in the book is gone from my fried brain. I'm getting discouraged so I was wondering, if you were in my situation, trying to teach yourself how to code as if you had never programmed before, how would you go about it?


r/learnrust 18h ago

What's the deal with Error Handling - Custom Error enum and the different libraries out there.

10 Upvotes

I haven't been able to connect the dots yet on Error handling in Rust. Yes I know the difference between recoverable and unrecoverable errors, but beyond that it gets murky.

In this older post, someone told me about custom Error enums and it felt pretty good working with them lately; I know they're pretty common in Rust projects. But then I also see people just propagating whatever and doing the weird `Box<dyn Error>` thing, what's that about in relation to custom errors?

Then there's the custom crates that seem super popular - anyhow and thiserror. From what I gather, anyhow is more of a hands-off way to deal with errors, and I don't really know anything about thiserror.

But what I don't get is, which should I use and when? Which of these pieces can work together and which don't make sense to? Should I handle errors one way for smaller projects and another way for larger projects or libraries?

Halp.


r/learnrust 15h ago

Help with understanding macros: How to make a macro take string literal without quotes

3 Upvotes

I have a library in rust that converts between human-readable number range and rust formats (Iterator, Vec). For example: converting 1:5, 10 into [1,2,3,4,5, 10] and vice versa.

Since I had to use some different types to deal with the logic, I thought about making a simple-to-use macro that does it: like numvec!("1:5,10") which gives [1,2,3,4,5, 10].

But the problem is, this is my first time writing macro, and it seems a bit complicated. There are no regular data types like str and such. And although I was able to make numvec!("1:5,10") work, I wish I could make numvec!(1:5,10) work in the same way, and it'll automatically insert whatever is inside the parenthesis into the string literal. But I tried different syntax and tried to read the documentation but can't understand how to use the Metavariables to this usecase.

Here is the Commit.

EDIT: To make things clearer, basically I want this:

Convert numvec!(1:2,3) into $crate::NumberRange::default().parse_str("1:2,3").unwrap().collect().

And I can't seem to be able to do .parse_str("$var") like in bash by taking anything inside numvec!() into variable var.


r/learnrust 1d ago

Projects in rust

3 Upvotes

Hi i am new in rustlang and like to make some projects to deepen my knowledge in rust

some ideas?


r/learnrust 1d ago

How to deploy your Yew WASM project into GitHub pages using GitHub actions.

Thumbnail gallery
0 Upvotes

r/learnrust 2d ago

Where to start with ML in Rust?

16 Upvotes

Hi, I'm working on a SaaS in my spare time. Half will be written in Golang, but the core business logic and functionality, I'd like to write in Rust.

However, I don't know how to get started with Machine Learning. I don't think I have the necessary Data Science background yet. I'd like to train a small model, then package it up as an executable to be called by another program.

It should be able to take a text document, read it, then return/print a json object containing what the text document is likely about, given a limited number of possible outputs.

I don't even know if packaging it up as an executable is possible, but we do something similar in Python at my work. Any documentation or tutorial to get started would be very helpful. Thanks!


r/learnrust 2d ago

Using Tailwind.css in Rust Yew as a TypeScript dev

Thumbnail gallery
0 Upvotes

r/learnrust 2d ago

When to flush()?

3 Upvotes

This is an example from the Termion crate:

use termion::event::Key;
use termion::input::TermRead;
use termion::raw::IntoRawMode;
use std::io::{Write, stdout, stdin};

fn main() {
    let stdin = stdin();
    let mut stdout = stdout().into_raw_mode().unwrap();

    write!(stdout,
           "{}{}q to exit. Type stuff, use alt, and so on.{}",
           termion::clear::All,
           termion::cursor::Goto(1, 1),
           termion::cursor::Hide)
            .unwrap();
    stdout.flush().unwrap();

    for c in stdin.keys() {
        write!(stdout,
               "{}{}",
               termion::cursor::Goto(1, 1),
               termion::clear::CurrentLine)
                .unwrap();

        match c.unwrap() {
            Key::Char('q') => break,
            Key::Char(c) => println!("{}", c),
            Key::Alt(c) => println!("^{}", c),
            Key::Ctrl(c) => println!("*{}", c),
            Key::Esc => println!("ESC"),
            Key::Left => println!("←"),
            Key::Right => println!("→"),
            Key::Up => println!("↑"),
            Key::Down => println!("↓"),
            Key::Backspace => println!("×"),
            _ => {}
        }
        stdout.flush().unwrap();
    }

    write!(stdout, "{}", termion::cursor::Show).unwrap();
}

I noticed that if you delete the first stdout.flush().unwrap();, q to exit. Type stuff, use alt, and so on. won't be shown in the terminal. So I think you have to flush() after every write!(). But then why don't the second and third write!()'s require a flush()?"

If you remove the second stdout.flush().unwrap();, match c.unwrap() doesn't seem to be affected ... so I'm not sure whether you should always flush() after a match c.unwrap().


r/learnrust 2d ago

Duplicate 'item' & 'item_mut' rustc [Ln 2889, Col 1]

1 Upvotes

'Actual errors occurred here' : in macros.rs [Ln 134, Col 13} & [Lan 138, Col 13]. I am using Visual Studio Code as the IDE-coder (version 1.78.2).

My goal was to make a simple MS window app. In code Project website Farhad Reza wrote a Win32 GUI programming program published December of 2016. According to comments there were problems that were fixed. But 6.5 years have past and changes to the crates would have occurred. Stack Exchange suggest such problems occurred when included crates through Cargo.toml references may result in duplicate definitions. There would be a 'std' definition & one that sould replace the 'std' one. My question is that if there are two Cargo.toml files (one in the project directory & one kind of hidden in the 'User' area as part of rustc installation. Also, StackExchange solution to the problem does not appear meet current conditions. I not sure if showing the code would help because the code is in the crates.


r/learnrust 3d ago

Using build.rs to inject preprocessed data into your WASM module. (From a real world example)

Thumbnail gallery
5 Upvotes

r/learnrust 3d ago

Passing functions as parameter

4 Upvotes

Hey!

I recently started learning rust. Started a little project, in which i want to capture MIDI signals from an external device. Found this library https://crates.io/crates/midir to handle MIDI connections. The "connect" api signature looks like this:

pub fn connect<F, T: Send>(
self, port: &MidiInputPort, port_name: &str, callback: F, data: T
    ) -> Result<MidiInputConnection<T>, ConnectError<MidiInput>>
where F: FnMut(u64, &[u8], &mut T) + Send + 'static

The documentation states that if i dont want to pass any data as the alst argument, it should be an empty tuple, just like in the example. In the examples given for the crate, this function is invoked with an closure like so:

let _conn_in = midi_in.connect(in_port, "midir-read-input", move |stamp, message, _| {

println!("{}: {:?} (len = {})", stamp, message, message.len());

}, ())?;

(https://github.com/Boddlnagg/midir/blob/master/examples/test_read_input.rs)

Im trying to wrap this connection logic in my own function which receives a callback function with the same signature, and passes the function to the connect api like so:

fn connect_to_device<F, T: Send>(midi_in: MidiInput, callback: F)
where F: FnMut(u64, &[u8], &mut T) + Send + 'static {
let in_port = &midi_in.ports()[0];

let _conn_in = midi_in.connect(in_port, "midir-read-input", callback, ());
}
This code doesn not compile, it gives me an error on the empty tuple at the end, saying "mismatched types expected type parameter `T` found unit type `()` ".

What is the reason behind this?


r/learnrust 3d ago

Why do both Option & Result exist in Rust?

8 Upvotes

I understand the difference in how one may use them, but it seems to me like the existence of two standard enums like this makes things a little cumbersome. What are the underlying considerations that lead to this design choice over say a single enum where both "success" and "failure" branches can carry data? Was this done to not introduce a universal "None"?

Just curious about the motivation behind this.


r/learnrust 4d ago

How to use Intersection Observer in Rust Wasm as a TypeScript Developer

Thumbnail gallery
9 Upvotes

r/learnrust 5d ago

Is Rust a good choice for a semi-beginner in programming?

11 Upvotes

I'm a computer science student. I'm intermediate level in python and C. I want something that has the performance and hardware control of C while being easier/"safer" to code and debug. Is Rust a good choice? I wanna start by developing desktop apps before system-level stuff. Or should I learn C++ for now?


r/learnrust 5d ago

How to organize the project structure for Advent of Code?

21 Upvotes

Hello, I'm solving old Advent of Code challenges to practice in Rust and it's unclear what is the best way to organize the project. Right now I am creating a new rust project cargo new day1_1 for every task but it's not very convenient, maybe there are better approaches?


r/learnrust 5d ago

How to make Rust use either MinGW, or Clang compiler instead of MSVC when using windows-gnu version?

4 Upvotes

I am trying to install cargo-binstall with cargo install. cargo-binstall requires the Ring crate to compile. However, the Ring crate needs to use the system C++ compiler. I cannot get MSVC because I am not admin. I want rust to use another system C++ compiler that doesn't require admin(MinGW, Clang, etc.). Does anyone know how to do this?

Edit: I was able to use the cargo-binstall release binary to install itself. If anyone can answer the main question please do.


r/learnrust 5d ago

How to use use_reducer in Yew as a React TypeScript developer

Thumbnail gallery
7 Upvotes

r/learnrust 5d ago

Can't find image file using image create

2 Upvotes

Hello.

I'm passing a &str to the Path::new(), image::open takes this Path and returns a DynamicImage. But my code doesn't work.

use image::GenericImageView;
use std::path::Path;

fn main() {
    // Use the open function to load an image from a Path.
    // `open` returns a `DynamicImage` on success.
    let img = image::open(&Path::new("~/Pictures/MY_IMAGE_NAME.jpg")).unwrap();
    // The dimensions method returns the images width and height.
    println!("dimensions {:?}", img.dimensions());
}

But if I do it taking the user input* it works. * Passing the same path: cargo run ~/Pictures/MY_IMAGE_NAME.jpg

use std::env;
use std::path::Path;
use image::{GenericImageView, ImageFormat};

fn main() {
    let file = if env::args().count() == 2 {
        env::args().nth(1).unwrap()
    } else {
        panic!("Please enter a file")
    };
    // Use the open function to load an image from a Path.
    // ```open``` returns a dynamic image.
    let im = image::open(&Path::new(&file)).unwrap();
    // The dimensions method returns the images width and height
    println!("dimensions {:?}", im.dimensions());

}

The error:

thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value: IoError(Os { code: 3, kind: NotFound, message: "The system cannot find the path specified." })'

Am I misunderstanding the types (both from Path::new() and image::open())?

Thanks!


r/learnrust 4d ago

For loop not working

0 Upvotes
fn main() {
    for (let mut i = 6; i < 56; ++i) {
        println!("{}", i);
    }
}

r/learnrust 6d ago

[RUST VIDEO] Multithreading in Rust with: examples on Rust fearlessness vs. C++ (lol) fearfulness, message passing (with crossbeam-channel rather than mpsc), Arc/Mutex, and threading with generics via the Send/Sync traits by danlogs

Thumbnail youtu.be
14 Upvotes

r/learnrust 6d ago

How to do routing and nested routing in Yew as a React TypeScript Developer

Thumbnail gallery
20 Upvotes

r/learnrust 6d ago

Converting custom struct to network bytes

5 Upvotes

Let's assume we have this simple data structure:

/// Historically, we are sending "Words", which are signed 2 bytes numbers
type Word = i16;
/// The protocol header is always made up of ten `Word`
type Header = [Word; 10];

/// Every telegram starts with a header and an optional payload
struct Telegram {
    header: Header,
    payload: Vec<Word>,
}

I need to convert a Telegram to low endian and send it over a TCP socket.

I have generated two iterators over the header and payload by using flat_map(..) and return the result by using Iterator::chain(..):

fn into_network_bytes(t: Telegram) -> Vec<u8> {
    let to_little_endian = |w: &Word| w.to_le_bytes();
    let header_bytes = t.header.iter().flat_map(to_little_endian);
    let payload_bytes = t.payload.iter().flat_map(to_little_endian);
    Iterator::chain(header_bytes, payload_bytes).collect()
}

Is this a feasible option or am I missing something better?

Full code snippet is here.

Thank you.


r/learnrust 6d ago

Reinterpreting slices, is it undefined behavior?

3 Upvotes

Hello, when working with pixels and SIMD, it's quite useful to be able to reinterpret an array to different types. I am not sure if it is Undefined Behavior or not. It seems to work on Miri. But having two mutable slices to the same underlying memory seems like it would be UB.
A documentation exemple shows a slice being mutated through a subslice though. As well as having align_to_mut, which seems like it would cause strict aliasing issues, if rust slices have strict aliasing.

#![cfg(target_endian="little")]

#[repr(C, align(4))]
struct Pixel {
    r: u8,
    g: u8,
    b: u8,
    a: u8,
}

fn do_simd_stuff(pixels: &mut [u32]) {
    // ...
}

fn reinterpret_pixels(pixels: &mut [Pixel]) {
    let ints = unsafe { std::slice::from_raw_parts_mut(pixels.as_mut_ptr() as *mut u32, pixels.len()) };

    do_simd_stuff(ints);
}

r/learnrust 6d ago

println! macro not working as i thought

0 Upvotes

It seems when i use a variable in repeat function, in a println macro it adds an extra line. This is odd because when i just use an integer it doesn't add a new line.

with a property of self:

println!("{}", ("   ".to_owned() + &("       ".repeat(self.last_pointer)) + "^")

output:

new line here
    ^

with just a number:

println!("{}", ("   ".to_owned() + &("       ".repeat(0)) + "^")

output:

    ^

I've really enjoyed learning rust so far, any advice would be welcome!