17

I'm slowly starting Rust for Rustaceans, and it's already poking holes in my understanding of Rust. Here's a couple initial questions I have:

A shared reference, &T is , as the name implies, a pointer that may be shared. Any number of references may exist to the same value, and each shared reference is Copy, so you can trivially make more of them

I don't understand why a shared reference has to implement copy. In fact, isn't this not true just by the fact that references work for Strings and Strings size can't be known at compile time?

  1. I'm having trouble with the idea of assigning a new value to a mutable reference.

let mut x = Box::new(42); *x = 84;

Why in this example, is the assignment dereferenced. Why not just do x=84? is it dereferenced specifically because is Boxed on the heap?

10

in sequelize (javascript) it's pretty straightforward to either find a record, or create it if it doesn't exist. I don't see anything similar with sea-orm. There's a 'save' method that seems to insert or update, but I need to know details about the record ahead of time :/

Any ideas?

https://sequelize.org/docs/v6/core-concepts/model-querying-finders/

0
submitted 1 year ago* (last edited 1 year ago) by nerdblood@programming.dev to c/rust@programming.dev

The first post had a couple errors that made things confusing. I have an accurately formatted JSON response, but I still can't seem to deserialize it.

I keep getting an error where the response isn’t matching up as expected: Error("data did not match any variant of untagged enum NationResponse"

I have a JSON response that looks like this:

 {
      {
            "id": 1,
            "country": "usa"
        },
        [
            {
                "id": 1,
                "age": 37,
                "name": "John"
            },
            {
                "id": 2,
                "age": 21,
                "name": "Nick"
            },
        ]
}

And I’m trying to deserialize it, but I can’t seem to get it right. Isn’t this accurate?

#[derive(Deserialize, Debug)]
#[serde(untagged)]
enum NationResponse {
    Nation(Nation),
    People(Vec),
}

struct Person {
    id : i32,
    age : i32,
    name : String
}

struct Nation {
    id : i32,
    country : String
}

Edit:

The problem I was actually experiencing was trying to use an enum as the response. Yes the formatting for my example was wrong (it should have been an array). But the structure besides that was accurate.

What I needed was Vec>

[-] nerdblood@programming.dev 4 points 1 year ago

Oh man, I didn't know debug_handler existed. Sure enough I had a missing derived attribute... not sure how but Serde serialize and deserialize were missing, so when I was trying to return Ok(Json(army)) it was failing. Thanks so much!

17

Not sure what happened exactly... it was working fine and I didn't change anything in this file. It has to be related to something I did recently:

  1. Ran a migration adding a unique constraint on a table
  2. Generated two new entities of a couple very basic tables.

The handler I'm using isn't even using the new tables, so I don't know why this randomly broke. Anyone have any ideas? Or even some guidance on how to decipher that obscure error would be helpful.

19

I've been trying to use OneCell, but I keep having errors trying to set it up to handle a mutable vector that I can push to.

I know there's going to be some answers telling me maybe not to use a singleton, but the alternative of passing a vector all around throughout my code is not ergonmic at all.

I've tried lots of things, but this is where I'm at right now. Specifically I'm just having trouble initializing it.

`/**

  • LOG_CELL
  • Stores a vec of Strings that is added to throughout the algorithm with information to report
  • To the end user and developer */ pub static LOG_CELL: OnceLock<&mut Vec> = OnceLock::new();

pub fn set_log() { LOG_CELL.set(Vec::new()); }

pub fn push_log(message: String) { if let Some(vec_of_messages) = LOG_CELL.get() { let something = *vec_of_messages; something.push(message); } } `

[-] nerdblood@programming.dev 4 points 1 year ago

Also, move out special types to types.rs, error types to errors.rs to keep the area with the actual algorithms more clear.

Ok this is totally something my code base needs. Very actionable feedback.

And yeah that's one of the things I love about rust; it will tell me everywhere things are out of wack. It's such a different experience from back when I had large JavaScript code bases. Make changes and pray lol.

[-] nerdblood@programming.dev 3 points 1 year ago

This is really good to hear, I don't think I'm as far off base as I thought; maybe I've been over thinking it a bit. And thanks for that refactoring resource. I'm very big into making my TS code clean and maintainable. I'm just thrown off a bit with the new paradigm.

26

I've mostly been putting functions, structs enums and tests in the same file and it's starting to feel like a mess... I am constantly losing track of which function is where and I'm never quite sure if I have code in the right place. I know this is kind of vague, but that's been my general feeling while working in my largest personal project so far. It's essentially a large Algorithm that has many smaller steps that needs to run in a sequence.

I think I might just have too many loose functions and maybe I should use more impl methods and traits? I'm also thinking I should try the builder pattern in a few spots.

Anyone have any guidance on code organization in rust?

2

I know there's mockall which seems to be geared towards implementation methods and traits, but I'm wondering about just structs with non-function properties.

In my tests, I want to define initialized structs with values. It works fine to just do it like I normally would in code, but I'm wondering if there's more to it than that. Like if I have a cat struct:

struct Cat { name : String } `

#[cfg(test)] pub mod test { use super::Cat; fn test_create_cat() -> Cat { Cat { name. : String::from("Fred") }; }

That's fine, but should I be doing it differently? What about mockall, is it not meant for structs with properties?

[-] nerdblood@programming.dev 3 points 1 year ago

Thanks, yeah it felt like too many tests to keep in file. I can live with that directory approach. TY!

9
submitted 1 year ago* (last edited 1 year ago) by nerdblood@programming.dev to c/rust@programming.dev

for example, I have a file structure that looks like this:

action/
   attack.rs
   attack.test.rs
   mod.rs

But this doesn't work in the mod file:

pub mod attack.test;

and neither does:

pub mod "attack.test";

[-] nerdblood@programming.dev 3 points 1 year ago

This is cool. I'm a front-end focused dev by trade and have been 11 years now. I've been picking up Rust as a side hobbie for 6 months or so and have not even peaked at these front-end frameworks. I know Lemmy is all about Rust, but I still think it's pretty cheeky they're using Rust for the front-end.

About Leptos specifically... If there's no shadow dom / rerenders and not trying to be react, I already like it better than it's competitor.

9
submitted 1 year ago* (last edited 1 year ago) by nerdblood@programming.dev to c/rust@programming.dev

I'm wondering with my game project how best to handle types. I'm basically fetching all the rows in a particular table and creating a struct to represent that data. I then have like 5 or 6 sequential steps I'm trying to go through where I need to modify those initial values from the db.

My first thought was to have a base type called 'BaseArmy', then I needed to add new temporary properties that are not in the db and not represented in the original struct, so I decided to create a new struct 'Army'. The problem is I keep running into errors when passing converting from BaseArmy to Army. I tried writing a From impl, but it wasn't working (and I'm not even sure if it's the approach I should be taking).

So should I:

  1. Have multiple different types to handle these kinds of cases
  2. Have just one type somehow where I add properties to it? If so, how? I recently tried using Options for the fields that are not initially available, and that seems to be working but it feels weird.
[-] nerdblood@programming.dev 3 points 1 year ago

This is fantastic, thanks for sharing!

[-] nerdblood@programming.dev 4 points 1 year ago

I might not need global state, the more I think about it. I'll start with passing a struct and see where that gets me, thanks!

[-] nerdblood@programming.dev 3 points 1 year ago

Yeah I tried out lazy_static, but the compiler was strongly urging me not to use it since it's being deprecated. Thanks, I didn't know about OneCell.

12

My program is small enough that in TS/JS I'd normally just store the data in some global variable to be access from whatever elsewhere in the app. But with Rust from what I can tell this doesn't seem to be a common practice. How should i handle this?

More specifically, I need to:

  1. program start, fetch data from my db (DONE)
  2. store this data somehow somewhere
  3. access said data (for read only in this use case)

Thanks for any insights here!

[-] nerdblood@programming.dev 13 points 1 year ago

Eh , its probably just temporary. People just had apps they've used for 10 years yanked away and it's jaring how it all went down. Of course people are going to want to talk about it.

31

I've been learning rust for a while now and a key tactic that's helped me along has been asking questions on reddit, often very specific to code I'm writing. I'll usually attempt a solution on my own until I'm sufficiently stuck then ask for help.

Can I post those questions here or is there a better community for it?

[-] nerdblood@programming.dev 7 points 1 year ago

It's basically the same premise. Link aggregator with a forum attached, where upvoted content rises to the top. She doesn't need to know how instances work in order to use it in the same way that she doesn't need to be a mechanic in order to drive her car.

[-] nerdblood@programming.dev 4 points 1 year ago

I've tried only Connect, and it's been great.

[-] nerdblood@programming.dev 3 points 1 year ago

I love lamp.

view more: next ›

nerdblood

joined 1 year ago