5

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?

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

Indeed it does haha, thanks

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/

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

🤣

We're a pretty darn good minor league baseball team if you ask me

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

It should be wrapped in an array, not an object. Then it's valid. The problem was that I was trying to use an enum.

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 2 points 1 year ago* (last edited 1 year ago)

I got the response wrong, here's what I'm using that isn't working:

enum NationResponse {
    Nation(Nation),
    People(Vec),
}

Why the heck can't I edit the original post after a comment is made?

[-] 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!

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

Thanks for the reply! I don't know what you mean by extensions, but the state is literally just the DB connection:

struct AppState { conn: DatabaseConnection, }

16

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.

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

Async I have a handle on, but I'll take a look at the others for sure.

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

One for now, theoretically many later.

Nice I've never used Rc. Maybe now's my chance to look into it.

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?

1

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?

1
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";

0

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.

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

Have you thought about wiping your comments? I had 1300 (more than I thought I would) and have no regrets.

view more: next ›

nerdblood

joined 1 year ago