thread_id
stringlengths
6
6
question
stringlengths
1
16.3k
comment
stringlengths
1
6.76k
upvote_ratio
float64
30
396k
sub
stringclasses
19 values
kg67jt
It says I need to close both of my label elements. Haven't I done that?
I think the message is thrown off because you didn't close the input tags. Also, opening and closing tags need to be indented the same amount.
30
ProgrammingQuestions
tkqyyc
I am new to rustc. Am I able to apply a #[derive()] to a type brought into scope with a use? I want to: use: foo::Bar; #[derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)] struct A { b: Bar; c: Car; } but this raises a compiler error: the trait 'Archive' is not implemented for 'Bar'
`derive` is only applied on declaration. You can't import a `struct` and change it with a `derive`. You'd have to actually go to the file where that `struct` was first declared and add the derive there. If that's not possible, you'd need to find a way to not have `Bar` participate in that `struct` to use that specific derive. Ps.: You can also just do what the `derive` is doing manually as well.
30
LearnRust
tmqc20
Clippy gives me the warning "use of 'expect' followed by a function call" regarding the following piece of code: `.expect(format!("Couldn't find position of {}", search_word).as_str());` and advises me to use `.unwrap_or_else(|| panic!("Couldn't find position of {}", search_word))` instead. Does anyone know why this is the case? Edit: Explanation of all the warnings Clippy gives, which I somehow only found now some time after being helped out in this thread: https://rust-lang.github.io/rust-clippy/master/index.html
`.unwrap_or_else(||)` is lazily evaluated, i.e. in your case the `format!()`/`panic!()` macros will get called only if the unwrapping fails. On the other hand, your `.expect()` will call `format!()` every time, even if the newly allocated string (the result of `format!()`) ends up not being used because the unwrapping succeeded. Clippy wants you to avoid an unnecessary allocation that `format!` may make.
310
LearnRust
tmqc20
Clippy gives me the warning "use of 'expect' followed by a function call" regarding the following piece of code: `.expect(format!("Couldn't find position of {}", search_word).as_str());` and advises me to use `.unwrap_or_else(|| panic!("Couldn't find position of {}", search_word))` instead. Does anyone know why this is the case? Edit: Explanation of all the warnings Clippy gives, which I somehow only found now some time after being helped out in this thread: https://rust-lang.github.io/rust-clippy/master/index.html
Because the argument to `expect` is evaluated in any case (as function arguments are always evaluated before the call) so Clippy warns that you’re potentially doing something expensive in *every* case even though it’s only needed in the *exceptional* case.
110
LearnRust
tnmcvl
I'm writing some code where I need to cast integers to float, but since the casting operation is something that happens very often in the script, I'd like to declare a constant and change the type of the casting from f32 to f64 in order to change all the casting operations immediately. Is it possible to do something like this in rust? const FLOAT: primitive type = f32; let x = 3 as FLOAT;
Are you looking for the [`type` keyword](https://doc.rust-lang.org/std/keyword.type.html)?
180
LearnRust
tnmcvl
I'm writing some code where I need to cast integers to float, but since the casting operation is something that happens very often in the script, I'd like to declare a constant and change the type of the casting from f32 to f64 in order to change all the casting operations immediately. Is it possible to do something like this in rust? const FLOAT: primitive type = f32; let x = 3 as FLOAT;
As already said, `type` is what you are asking for. You can use it for the function and struct signatures to quickly change. But as for the casting, eventually consider using `try_from` and `from` in place of `as` to ensure the casts don't cause unnecessary panics or unexpected behavior, especially if you want to swap across the board. Rust's type-inference, combined with using `type`, can make non-panicking code that behaves consistently, and `as`, though convenient, has a bunch of possible changes. See https://rust-lang.github.io/rust-clippy/master/#as_conversions and the mentioned clippy lints for what I'm referring to.
40
LearnRust
tp5tij
I've read a file to a String, and it ends with a '\n' which makes me unable to convert it to a float, before moving on with other operations. I know that '/n' will have position 5, which makes hesitate between turning the string_var mutable and using string_var.pop() or going with string_var[0..5]. Are there any advantages with either of them which I should know?
I would use [`.trim_end()`](https://doc.rust-lang.org/std/primitive.str.html#method.trim_end) (or `.trim()` if there might be whitespace at the beginning as well.)
120
LearnRust
tp5tij
I've read a file to a String, and it ends with a '\n' which makes me unable to convert it to a float, before moving on with other operations. I know that '/n' will have position 5, which makes hesitate between turning the string_var mutable and using string_var.pop() or going with string_var[0..5]. Are there any advantages with either of them which I should know?
I might be wrong on some details but: Slice will create a new stack variable Pop will (try to) get the last element and return it So generally slice should have better performance. You could also use `.truncate` which wouldn't do any bonus allocations or returns. But unless it is some performance-heavy code all of them should do fine. And if it is, benchmarks are the way to go.
30
LearnRust
tptxcp
Doing rustlings I ran into match tuple { (r @ 0..=255, g @ 0..=255, b @ 0..=255) => Ok(Color{ red: r as u8, green: g as u8, blue: b as u8, }), ... I never ran into syntax like this before and would like to read more about it but all I found was one line in the book. [The book appendix](https://doc.rust-lang.org/book/appendix-02-operators.html)
It's a part of [identifier patterns](https://doc.rust-lang.org/reference/patterns.html#identifier-patterns). It matches the pattern on the right side of `@` and gives the name on the left side to the whole matched value
120
LearnRust
tqey6a
I know how to print a set number of decimals, and leading white space/zeros, but I'd like to print only 3 digits of a float I'm handling (which I assume never will be > 1000, but can't guarantee won't have fewer digits than 3). Is there some built in way to do this? I can only come up with very convoluted/naive ways to achieve this myself. To clarify, the following floats should be printed in the corresponding way: 123.45 -> 123; 12.345 -> 12.3; 1.2345 -> 1.23 Example of a convoluted/naive solution: let float\_to\_print: f64 = 12.345; let non\_digit\_numbers = float\_to\_print.round().to\_string().len(); println!{"{:.\*}", 3-non\_digit\_numbers, float\_to\_print}; ​ Edit: Another possible solution which almost works, and seems better: let float\_to\_print: f64 = 12.345; let float\_string = float\_to\_print.to\_string(); let float\_to\_print\_trimmed = float\_string\[0..4\].trim\_end\_matches('.'); println!("{float\_to\_print\_trimmed}"); [https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=fb51b9a50c358198a76ae8493e06836d](https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=fb51b9a50c358198a76ae8493e06836d) The logic of the last solution is that if I want at least one decimal to be printed, there will be in total 4 chars (including the period). If there are no decimals to be printed, the slice will leave the string with a trailing period, which is fixed with trim\_end\_matches('.'). The issue which remains is that there's no guarantees that the digit won't have fewer digits than 3, which can be solved with some match-statement, but I'd prefer something that uses less resources.
`format!(“{:3}”, my_float)`
90
LearnRust
tqkemv
Hello everyone, I'm trying to implement some strong types for my application like `CharIndex(usize)` and `ByteIndex(usize)` which both wrap a simple number. I want these types to have basic math functions like `Add` , `Sub` , etc. which operate on the inner number. However, I don't want to have to implement all of them for every new wrapper type I make. Is there a way (or a crate) that allows reuse of the implementation of a type but with a different name? Or does nothing like that exist yet? I think writing a macro could be a solution, but I haven't written macros before and I'm wondering if there's a better solution. ​ Note that a type alias is not what I want, since I would still be able to pass a `CharIndex` to a function which requires a `ByteIndex` (because they are the same type internally).
You can use macros to implement various traits and methods for many types at once. This is the price you pay with a new type pattern, you have to explicitly define all the methods.
30
LearnRust
tqkemv
Hello everyone, I'm trying to implement some strong types for my application like `CharIndex(usize)` and `ByteIndex(usize)` which both wrap a simple number. I want these types to have basic math functions like `Add` , `Sub` , etc. which operate on the inner number. However, I don't want to have to implement all of them for every new wrapper type I make. Is there a way (or a crate) that allows reuse of the implementation of a type but with a different name? Or does nothing like that exist yet? I think writing a macro could be a solution, but I haven't written macros before and I'm wondering if there's a better solution. ​ Note that a type alias is not what I want, since I would still be able to pass a `CharIndex` to a function which requires a `ByteIndex` (because they are the same type internally).
Search on lib.rs for #newtype tag. I just did and found a few interesting takes on making newtypes more convenient: https://lib.rs/crates/shrinkwraprs https://lib.rs/crates/phantom_newtype Shrinkwrap supports the macro approach and allows you to derive shrinkwrap and be able to access the inner value from the newtype in various ways. phantom_newtype provides 3 *structs* that implement commonly required traits and are generic over a tag which is used to make them unique to your type using phantom data. It's readme has examples. Shrinkwraprs is much more battle hardened, popular, recently updated. I went to lib.rs to find it and stumbled upon phantom_newtype having never heard of it. phantom_newtype is really clever and I like the idea. It reminds me of [ghost_cell](https://lib.rs/crates/ghost-cell) and [slotmap](https://docs.rs/slotmap/latest/slotmap/) in some ways. People are able to do clever things with generics! I think you will find yourself more restricted compared to shrinkwrap, and the generics might make the code size bigger/smaller (I'm unsure) compared to shrink-wrapped newtypes. There's also usage which looks the same as phantom_newtype but newer and only one struct. Usage has a less informative readme but you should review it if you are thinking of using a "phantom-style" newtype.
30
LearnRust
tquups
Hi, Yes, another borrow checking challenge... The tools I have gathered so far dont work in this instance so Im in need of some help Imagine a building structure that has floors, floors have apartments, and apartments have rooms. Rooms can have a depth, but also a min\_depth. The challenge is to make sure all rooms in de building should have the largest min\_depth as depth. I made a small code sample here, but note that there is one thing that is very important: The call to update\_building MUST be in the for loop, because the consecutive updates depend on the result of update\_building. This is not reflected in the code example. in other words, the `room.mindepth < room.depth` if statement in reality is a lot more complicated [https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=8a83ba92a1371f5d9837d589b0fdd9e6](https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=8a83ba92a1371f5d9837d589b0fdd9e6) I tried solving this in the following ways: \- using loops that use non-mutable variables. \- using `while` loops and indices. Since I still need references to the apartments and rooms this also fails. \- using `for index in 0..list.len()` kind of loops \- cloning the building to use different versions in the for loop and in the `update_building`. This doesnt work of course since the update depends on previous updates. All of these run into borrow checker problems, except for the last one that doesn't give correct results
Welcome to Rust! This is a classic case of *iterator invalidation.* The problem is that if you modify the building the `for` loop indices may now be invalid, or at least may have unintended values: the number of items at each level might be affected by the building update. This is a problem for most any imperative language, not just for Rust: the difference is mainly that Rust will catch it at compile time. In what way does a building update depend on previous updates? Does the structure of the building change? If so, you'll have to think carefully about your algorithm and how to get it to work right in this case.
60
LearnRust
trn92p
I assembled a Computer Science Curriculum that helps practice the acquired academic knowledge in Rust. If you want to learn systems programming in Rust or just be a better programmer, this is for you! Critiques and Contributions are welcome!
Thanks, I'll go over it at some point, just not now 😄
50
LearnRust
trn92p
I assembled a Computer Science Curriculum that helps practice the acquired academic knowledge in Rust. If you want to learn systems programming in Rust or just be a better programmer, this is for you! Critiques and Contributions are welcome!
Awesome
30
LearnRust
tsyuhb
Hello, everybody. So I am trying to create simple file reading system, basically you can create file and write into it or you can load a file and read whats inside of it, and I am stuck at writing stuff into a file. This is my code for reading and displaying data from a file fn load_file(){ print!("File to load "); let file_name = get_input(); let file = File::open(&file_name); match file{ Ok(f) => { let reader = BufReader::new(f); println!("##### DISPLAYING DATA FROM FILE {} #####", &file_name); for (_,line) in reader.lines().enumerate(){ let line = line.unwrap(); println!("{}",line); } println!("\n "); load_menu(); }, Err(_) => { println!("\n ####### ERROR CAN'T LOAD FILE ####### \n"); load_menu(); } } } And this is my code for creating the file and writing data into it fn get_input() -> String{ let mut input = String::new(); print!("> "); io::Write::flush(&mut io::stdout()).expect("flush failed"); match io::stdin().read_line(&mut input){ Ok(_) => String::from(input.trim()), Err(_) => String::from("Error, Wrong Input") } } fn create_file(){ print!("Name of the file to create "); let file_name = get_input(); let file = File::create(&file_name); match file{ Ok(_) => { println!("##### CREATING FILE {} #####", &file_name); let user_input = get_input(); match file.write_all(user_input.as_bytes()){ Ok(_) => { println!("Data has been writen into the file !") }, Err(_) => { println!("ERROR: Can't write into file") } }; load_menu(); }, Err(e) => { println!("{}",e); println!("\n ####### ERROR CAN'T CREATE FILE ####### \n"); load_menu(); } }; } I had tried using this fn write_into_file(){ let user_input = get_input(); let file = File::open("file.txt").unwrap(); file.write_all(user_input.as_bytes()).unwrap(); } However this doens't work at all. I had followed the e-book provided by the Rust, but there is nothing about working with files. ​ Anybody know better way of saving user Input into a file ?
You didn't get the file handle out of the result of `File::create` https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=6d8ecb9f22174a53aaebfa378b8812d1
80
LearnRust
tt7z8k
I am using the `rust-decimal` crate here If I use the following code to convert from `Decimal` to `f64`, everything works fine: ```rust use rust_decimal::prelude::ToPrimitive; // Create some decimal let decimal_val: Decimal = Decimal::new(1, 1); // Convert to f64 let f64_val = decimal_val.to_f64(); ``` But if I want to avoid the import, and `rust_decimal` is in `Cargo.toml`. I should be able to write this as: ```rust // Create some decimal let decimal_val: Decimal = Decimal::new(1, 1); // Convert to f64 let f64_val = decimal_val.rust_decimal::prelude::ToPrimitive::to_f64(); ``` This fails with the error ```rust let f64_val = decimal_val.rust_decimal::prelude::ToPrimitive::to_f64(); ^^ expected one of `(`, `.`, `;`, `?`, `else`, or an operator ``` I think I have may have the wrong syntax since this should be possible...
I assume the function rust_decimal::prelude::ToPrimitive::to_f64 do exists and takes a self argument. You should use the following: let f64_val = rust_decimal::prelude::ToPrimitive::to_f64(decimal_val)
30
LearnRust
tt7zgk
I was learning rust but I dropped the idea because I can't find any videos/articles which explain rust memory management system easily possible. I've found many videos but they just go over my head. Any resource would be helpful!
To summarize as briefly as possible... (and I think there's something like this in the O'Reilly crab book...) Every time the Rust compiler compiles your code, it's also constructing an automated proof that no piece of memory can be leaked, double-freed, become part of a pointer loop, get accessed by two threads at the same time, etc, etc, etc. And if you write your code in such a way that the compiler CAN'T construct such a proof... then the compiler just plain won't compile your program! Now of course you can use `unsafe{}` blocks to write code that *you're* sure are safe. But if those actually turn out to be UNSAFE and there's a memory leak or pointer loop or double-free in them that you didn't notice... guess who's to blame? Hint: NOT the compiler! This is what all that ownership and lifetimes and mutable reference stuff boils down to. All those things are ways to manage memory, that the compiler understands well enough so it construct a memory correctness proof when it compiles your program. If you want to know more about any specific one of those, and how it allows the compiler to know that memory management is being done correctly, then ask away. I'll do my best to answer. And if I don't know the answer, there's a good chance someone else here does.
100
LearnRust
tt7zgk
I was learning rust but I dropped the idea because I can't find any videos/articles which explain rust memory management system easily possible. I've found many videos but they just go over my head. Any resource would be helpful!
Rust memory management is just like fairly simple C memory management, except the compiler ensures you have one mutable reference or one-or-more immutable references to any given memory. But you still use stack allocations or you malloc() space, and free() gets called when the last reference goes out of scope. There are complexities on top of that (just like there's sbrk() in C that almost nobody needs to know about), but those are implementation details you probably don't need to know if you're just writing pure Rust and not (say) jumping into other programming languages or calling the OS or implementing the OS yourself.
50
LearnRust
ttf6bh
I have a string of file contents: `let file_contents = fs::read_to_string("myfile.txt").unwrap();` And I have some threads. The first should read the first k lines in the string (lines in the file), the second the next k, etc. The string itself is never modified (not mut). It may be that (k * number_of_threads) is greater than the number of lines in the file, in which case there should be wrap around (a Cycle iter works well). The wrap around means it is possible that the threads are not necessarily looking at distinct lines. How could I do this in Rust? Currently I have, let mut cycle_iter = file_contents.lines().cycle(); for i in 0..num_threads { ... let processor = Processor::new(cycle_iter.clone()); for _i in 0..per_thread_workload { cycle_iter.next(); } let thread = spawn(move || processor .run()); threads.push(thread); } I'm having issues with lifetimes 69 | let mut cycle_iter = file_contents.lines().cycle(); | ^^^^^^^^^^^^^^^^^^^^^ | | | borrowed value does not live long enough | argument requires that `file_contents` is borrowed for `'static` Is the problem that my threads may outlive the function which `file_contents` exists in (it won't because I join the threads before exiting, but I guess the compiler can't tell), meaning their iterators would be referring to garbage? If so, how can I fix this? I tried putting my string on the heap (I vaguely remember doing this for mutex so that multiple threads can make use of it properly): let file_contents = Arc::new(fs::read_to_string("data/packages.txt").unwrap()); but still same problem.
You might want to take a look at a crate called rayon. It handles parallel iterations for you quite nicely. If it doesn't fit your needs, maybe the brand new [scoped threads api](https://doc.rust-lang.org/nightly/std/thread/fn.scope.html) will do? I just saw that it haven't landed in stable yet, thought it did in 1.61.
60
LearnRust
tu02ey
Does anyone have any articles, videos or walkthroughs that I can utilize to learn how to build REST APIs? I just finished an introductory course and wanted to build out a CLI application that would return the definition of an inputted word. I was planning on using the [Merriam-Webster api](https://dictionaryapi.com/products/api-collegiate-dictionary). I'm sure this exists as a crate, I just wanted to get the experience myself. Thanks in advance.
I haven't read the full book but I think zero to production in rust would cover what you're trying to learn. https://www.zero2prod.com/ I don't know of any free tutorials or videos that cover what you are asking better than that book, but there are a few other places you might look for more general rust info: https://thesquareplanet.com/ - his YouTube channels is fantastic. https://fasterthanli.me/ - a great blog with rust info. These YouTube channels have rust info also, but not quite as much my first 3 suggestions. https://youtube.com/channel/UCRA18QWPzB7FYVyg0WFKC6g - this YouTube channel also covers rust topics. https://youtube.com/channel/UCDmSWx6SK0zCU2NqPJ0VmDQ - this channel has a web app series that may be useful. Good luck!
100
LearnRust
tu02ey
Does anyone have any articles, videos or walkthroughs that I can utilize to learn how to build REST APIs? I just finished an introductory course and wanted to build out a CLI application that would return the definition of an inputted word. I was planning on using the [Merriam-Webster api](https://dictionaryapi.com/products/api-collegiate-dictionary). I'm sure this exists as a crate, I just wanted to get the experience myself. Thanks in advance.
Hopefully these are helpful: [https://tms-dev-blog.com/jwt-security-for-a-rust-rest-api/](https://tms-dev-blog.com/jwt-security-for-a-rust-rest-api/) [https://tms-dev-blog.com/how-to-implement-a-rust-rest-api-with-warp/](https://tms-dev-blog.com/how-to-implement-a-rust-rest-api-with-warp/)
30
LearnRust
tuu3rc
The _sync_ version of reading/writing files is as per the [rust docs](https://doc.rust-lang.org/std/fs/struct.OpenOptions.html): use std::fs::OpenOptions; let file = OpenOptions::new() .read(true) .write(true) .create(true) .open("foo.txt"); How do you do this same thing [_async_ using tokio](https://docs.rs/tokio/latest/tokio/io/trait.AsyncWriteExt.html)? I only see basic examples like this: use tokio::io::{self, AsyncWriteExt}; use tokio::fs::File; #[tokio::main] async fn main() -> io::Result<()> { let data = b"some bytes"; let mut pos = 0; let mut buffer = File::create("foo.txt").await?; while pos < data.len() { let bytes_written = buffer.write(&data[pos..]).await?; pos += bytes_written; } Ok(()) } I am new to rust and am looking for how to achieve the equivalent of the [Node.js API](https://nodejs.org/docs/latest-v9.x/api/fs.html#fs_fs_open_path_flags_mode_callback), where you specify the file's mode and flags for read/write/create/append/etc.. Not sure the Rust way of doing this async.
Tokio has OpenOptions: https://docs.rs/tokio/latest/tokio/fs/struct.OpenOptions.html However, keep in mind that file I/O in Tokio is quite slow. If you need it to be fast and async, consider tokio-uring.
40
LearnRust
tvkip4
Hi, I'm creating a project which calls an external API and I wanted to create an API client struct which holds all the methods for different calls to the API. So I created the stuct, but it grows and grows and the method names are getting longer because the methods call endpoints about different resources. Example: get_resource_by_id(id) get_resource_comments_page(resource_id, page_number) ... And similar for few more resources (about 8-10) I was wondering if there is a better way to compose the api client, because now the struct is really bloated. My ideas are: 1. Create a api client per resource (e.g. UserApiClient have all methods about handling user endpoints). 2. Similar to idea 1, but have all of these api clients under one struct as public members (or hidden behind getters) so you can call it e.g. `apiClient.user.get_by_id(id)` 3. Having functions without struct at all, composed into different modules (so you need to call this with use of module name like `users::get_by_id(id)` and `posts::get_by_user_id(user_id)`) Which idea should I go for? Or maybe all of this is garbage? What would be the most idiomatic way?
Why not use a trait? Or several traits? Exposing a struct much less it's fields like this seems like a mistake imo. Traits are nicer because you can group several similar methods together, but abstract them from the implementation. Making struct fields public also makes them mutable, which might invalidate the struct. It's generally best to only expose fields through immutable methods, and validate constructors / mutable methods to catch invalid inputs at their source.
40
LearnRust
tvkip4
Hi, I'm creating a project which calls an external API and I wanted to create an API client struct which holds all the methods for different calls to the API. So I created the stuct, but it grows and grows and the method names are getting longer because the methods call endpoints about different resources. Example: get_resource_by_id(id) get_resource_comments_page(resource_id, page_number) ... And similar for few more resources (about 8-10) I was wondering if there is a better way to compose the api client, because now the struct is really bloated. My ideas are: 1. Create a api client per resource (e.g. UserApiClient have all methods about handling user endpoints). 2. Similar to idea 1, but have all of these api clients under one struct as public members (or hidden behind getters) so you can call it e.g. `apiClient.user.get_by_id(id)` 3. Having functions without struct at all, composed into different modules (so you need to call this with use of module name like `users::get_by_id(id)` and `posts::get_by_user_id(user_id)`) Which idea should I go for? Or maybe all of this is garbage? What would be the most idiomatic way?
For my crate I copied the design presented here for the gitlab crate: https://plume.benboeckel.net/~/JustAnotherBlog/designing-rust-bindings-for-rest-ap-is
30
LearnRust
twqhet
I've recently started experimenting with Rust, following the [The Rust Programming Language](https://doc.rust-lang.org/book/title-page.html) book. In [Chapter 2](https://doc.rust-lang.org/book/ch02-00-guessing-game-tutorial.html) a simple tutorial for building a guessing game is introduced. The program generates a random number and the user tries to guess it. I want to implement a function `get_input` responsible for reading and validating the user's input. Until a valid input is given, the program should keep prompting the user for a number. I don't understand why, but the whole `input = match buffer.trim().parse::<u32>() {...}` block is marked as an "unreachable expression". For sure there are better ways to implement this, but I'd be grateful if someone could help me understand what's wrong with this specific piece of code and how to fix it. ``` fn get_input() -> u32 { let mut input: u32; loop { println!("Enter a number:"); // read input from stdin and store it in buffer let mut buffer = String::new(); io::stdin() .read_line(&mut buffer) .expect("Failed to read the line."); // if input is not a number stay in the loop, otherwise break out input = match buffer.trim().parse::<u32>() { Ok(num) => { num; break; } Err(_) => { println!("Invalid input."); continue; } }; } input } fn main() { let input: u32 = get_input(); println!("{}", input); } ```
If I understand it correctly, neither the Ok or Err branch return anything, since one breaks outside of the loop and the other continues the loop. Hope that helps
40
LearnRust
tx3wdl
I don't get any Rust analyzer hints when I am working on rustlings. My work around is I just copy it to the playground where I do get some rls(?) help. Could my issue be not launching VSCode from the correct folder? I usually just open the next file and not any folder in particular.
If I recall correctly you have to open the rustlings folder containing the Cargo.toml file.
30
LearnRust
ty9ej0
The error I get is as follows: thread 'main' panicked at 'Git is needed to retrieve the soloud source files!: Os { code: 2, kind: NotFound, message: "No such file or directory" }', /home/steve/.cargo/registry/src/github.com-1ecc6299db9ec823/soloud-sys-1.0.2/build/source.rs:17:10 and my Cargo.toml file contains this: \[package\] name = "audiotest" version = "0.1.0" edition = "2021" \# See more keys and their definitions at [https://doc.rust-lang.org/cargo/reference/manifest.html](https://doc.rust-lang.org/cargo/reference/manifest.html) \[dependencies\] soloud = "1.0.2" ​ Does anyone know what's going wrong and/or how to fix it?
>Git is needed to retrieve the soloud source files! Install git
30
LearnRust
tydufm
Hey ! I'm trying to retrieve the mode of a file in Rust, for that I'm using std::fs::FileType. for that I create a function that return a FileType : use std::fs // s parameter stands for a file path fn file_mode(s: &String) -> fs::FileType { return fs::metadata(s).unwrap().file_type(); } and this function return is : FileType(FileType { mode: 33188 }) I can't, and to know how can access that **mode** property ? ​ Thanks
By "mode" do you mean ["permissions"](https://doc.rust-lang.org/stable/std/fs/struct.Permissions.html) ? fn permissions(path: &str) -> std::io::Result<std::fs::Permissions> { let metadata = std::fs::metadata(path)?; metadata.permissions() } Most std::fs structs have extension traits only available on particular platforms, for example the [`PermissionsExt`](https://doc.rust-lang.org/stable/std/os/unix/fs/trait.PermissionsExt.html) trait. [playground](https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=a502f354a406a53416de9620eeb927dc) You can find the platform specifics [extension traits here](https://doc.rust-lang.org/stable/std/os/index.html).
40
LearnRust
tyqevp
Whenever I try to build with Cargo, I now get this error: CMake Error at CMakeLists.txt:45 (add\_compile\_definitions): Unknown CMake command "add\_compile\_definitions" ​ It's obviously an issue with Cmake, but I have Cmake installed and I've tried updating it, but still nothing, I looked up a solution, but all I couldn't find a solution related to Rust/Cargo If anyone knows what's up and can give me a hand, it would be greatly appreciated
One of your dependencies is calling CMake, most likely as part of its build script. Your version of CMake does not support all of the commands in the CMakeLists file the dependency is invoking. Your error should contain a lot more information regarding which crate is causing the error, start looking for that and see if you can locate the CMake script itself. Rust / Cargo should not be relevant other than them invoking the dependency's build script, so looking for help with CMake (or your dependency) in general should be enough. With no context other than parts of error text that's really all I can say. Neither Rust nor Cargo uses CMake, so the issue should be caused by one of your dependencies. Start looking at any crates you're pulling in that link to C/C++ libraries. If you can't find cause, put a minimal repro on GitHub or similar and I'll take a look at it.
30
LearnRust
u0139a
I am having a problem running `cargo wasm` on a rust project and I'm afraid that it's related to the fact that I'm using an m1 mac. I did the following commands. `cargo generate --git https://github.com/baedrik/snip721-reference-impl.git --name my-snip721` `cd my-snip721` `cargo wasm` This particular repo is designed to be compiled to wasm with the command `cargo wasm` and I know it works perfectly on Windows. When a ran `cargo wasm` on my m1 mac I got an endless string of similar errors. They mostly all follow this format: ``` error[E0433]: failed to resolve: use of undeclared crate or module `slice` --> /Users/<myusername>/.cargo/registry/src/github.com-1ecc6299db9ec823/byteorder-1.4.3/src/lib.rs:1594:13 | 1594 | slice::from_raw_parts(src.as_ptr() as *const u64, src.len()) | ^^^^^ use of undeclared crate or module `slice` ``` I also got a bunch of errors that followed this format. ``` error[E0425]: cannot find function `copy_nonoverlapping` in this scope --> /Users/<myusername>/.cargo/registry/src/github.com-1ecc6299db9ec823/byteorder-1.4.3/src/lib.rs:1950:13 | 1950 | copy_nonoverlapping( | ^^^^^^^^^^^^^^^^^^^ not found in this scope ... 2301 | unsafe_write_slice_native!(src, dst, u32); | ----------------------------------------- in this macro invocation | = note: this error originates in the macro `unsafe_write_slice_native` (in Nightly builds, run with -Z macro-backtrace for more info) ``` So what seems to be the problem. FYI, I'm using the terminal in visual studio code to run the commands. My mac is an m1 MacBook Pro (16-inch, 2021) running Monterey and I have rustup and cargo updated.
I think you're missing the `wasm32-unknown-unknown` target. You'll get further after running: rustup target add wasm32-unknown-unknown But you're going to run into an issue with the `secp256k1-sys` crate, as the non-rust code won't compile. See: [https://github.com/rust-bitcoin/rust-secp256k1/issues/283](https://github.com/rust-bitcoin/rust-secp256k1/issues/283)
30
LearnRust
u0dla0
use chrono::NaiveTime; let match_time; if let true = NaiveTime::parse_from_str(&match_time_str, "%H:%M:%S").is_ok() { match_time = Some(NaiveTime::parse_from_str(&match_time_str, "%H:%M:%S").unwrap()) } else { match_time = None }
let match_time = NaiveTime::parse_from_str(&match_time_str, "%H:%M:%S").ok();
80
LearnRust
u0dla0
use chrono::NaiveTime; let match_time; if let true = NaiveTime::parse_from_str(&match_time_str, "%H:%M:%S").is_ok() { match_time = Some(NaiveTime::parse_from_str(&match_time_str, "%H:%M:%S").unwrap()) } else { match_time = None }
If you don't care about any error handling, then you would achieve the same thing with: ```let match_time = NaiveTime::parse_from_str(&match_time_str, "%H:%M:%S").ok()``` Documentation on [ok](https://doc.rust-lang.org/std/result/enum.Result.html#method.ok) from Rust docs
30
LearnRust
u0elgk
Is it possible to match String or str with enum cases? Perhaps with some casts?Or it just does not make sense? enum Command { add, edit, } fn read_command(arguments: &[String]) { let command = &arguments[0]; let word = &arguments[1]; match String::from(command) { Command::add => println!("Add command"), Command::edit => println!("Edit command"), _ => println!("Something else"), } } Obviously I've got an error "**expected struct std::string::String, found enum Command**"
There's a million different ways you can handle this. I'll show a couple different ones. First: This one is your current issue which can easily be fixed. I just removed the enum and matched based off of &str. [Code Example](https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=fd7cdde0deed8a48edf0e98562af6278) Second: This one uses the enum with data in it and instead of using your &\[String\] we use that enum. [Code Example](https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=85e642ecf9b53834d025c814dfdc4055) Again, there are more ways you can do this. I recommend experimenting and looking at the [Rust Book](https://doc.rust-lang.org/book/ch06-00-enums.html) for more information. I always recommend using the way that makes the most sense to you. Because if you don't know how it works then how will you fix/edit it when the time comes. And ask questions, I or someone else can answer them.
140
LearnRust
u0kvp7
Several accounts have been sending unsolicited offers to give medical advice in exchange for money or "coffee." These are a violation of this subreddit's rules and likely Reddit's policies against spam. Moderators here can ban accounts from posting here, and we do, but we have no authority over DMs and chats. If you receive such a message, you're welcome to report it to us, but there is little more we can do. **Please flag the message/chat as spam, and please report at** [**https://www.reddit.com/report**](https://www.reddit.com/report) **for admin attention!** The only thing that can make the spam stop is Reddit administrators, and apparently the only thing that might make them take action is constant pressure.
If anyone gives you medical advice and THEN asks for money or something in return tell em to get stuffed. Anyone withholding genuine medical advice for the same reason then tell them u got a prescription for 2 of these 🖕🏾suppositories and that they need to complete the course taken 3 x a day with l a rusty meshed glove. I can only speak for myself, i dont get paid anywhere near my american counter parts but i am not here to make money (there are much easier and better ways with our knowledge and legitimate qualifications nevermind the ethical dilemma it unfolds) just to help people who may feel they have nowhere else to turn. If any one is in this situation and is being restricted information about their health then u can DM and i will try my best or highlight this in a post here - naming and shaming - and the rest of us will hopefully band together to help with your problem. No one is on this sub to make money and anyone who acts like they are should get an ethical slap from my four prima facie fingers + thumb. Especially a coffee. That just sounds like a dick manoeuvre
150
AskDocs
u0kvp7
Several accounts have been sending unsolicited offers to give medical advice in exchange for money or "coffee." These are a violation of this subreddit's rules and likely Reddit's policies against spam. Moderators here can ban accounts from posting here, and we do, but we have no authority over DMs and chats. If you receive such a message, you're welcome to report it to us, but there is little more we can do. **Please flag the message/chat as spam, and please report at** [**https://www.reddit.com/report**](https://www.reddit.com/report) **for admin attention!** The only thing that can make the spam stop is Reddit administrators, and apparently the only thing that might make them take action is constant pressure.
Is it verified medical professionals doing this?
50
AskDocs
u1d7av
Other than it works already why not get rid of using clib and use a rust native but functionally **equivalent** "rlib" at some point. Would there be a fundamental reason it would have to be a breaking change?
Because c-lib is already in place on the target system making static binaries small and easy to install.
120
LearnRust
u1d7av
Other than it works already why not get rid of using clib and use a rust native but functionally **equivalent** "rlib" at some point. Would there be a fundamental reason it would have to be a breaking change?
Partly, because your system call APIs are defined in terms of C types and calling conventions. As described in [this excellent blog](https://gankra.github.io/blah/c-isnt-a-language/). You could maybe figure out how to call fork or read directly with pure rust for a given architecture (not the c wrappers, but the system call interface directly), but doing so would be much more difficult than just calling the c wrappers, which have already been ported to all the architectures. Rust standard library already replaces much of the c standard library outside of the system service APIs.
100
LearnRust
u1hldq
See https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=4401bd55f8a59cb6f22385f8b8f3338f fn main() { let mut stack = Vec::new(); stack.push(1); stack.push(1); stack.push(stack.pop().unwrap() + stack.pop().unwrap()); println!("{}", stack.pop().unwrap()); } seems the only way is to allocate temp variable like let b = stack.pop().unwrap(); let a = stack.pop().unwrap(); stack.push(a + b); is there a way I'm missing?
You can write let total = stack.pop().unwrap() + stack.pop().unwrap(); stack.push(total); But yeah, short of doing some really weird stuff that wouldn't be better that's about as good as it gets. It would be nice if the borrow checker was precise enough to figure this out, but it's currently not: it doesn't understand that the borrows in the argument to `push()` can complete before `push()` is called.
80
LearnRust
u23yrt
The process for replies to serious questions on r/ask requires commenters to begin a comment reply with `answer:`. Any replies that don't begin with that syntax are removed. This is a very blunt solution to the problem of redditors' attempts to be hilarious in comments where the OP has requested only serious discussion. This has been a source of frustration for many of you who are posting well-intentioned replies that are being auto removed for not following the required syntax. Be advised that we have heard your feedback and are taking it into consideration to determine how we can best improve this process for the entire r/ask community. We hope to strike a better balance between removing joke/non-serious replies to threads with the `serious replies only` flair and permitting the actual serious replies. We've heard you in modmail and in the comments and will return soon with an announcement on what direction we'll take. Whatever form the new process takes, it will likely involve a greater role for user reporting so please remember that user reports are the fastest and best way to inform the moderator team of any issues with posts, comments, or users in the community. Thank you for your feedback on this issue and for your continued participation on r/ask. -r/ask mod team
I don't see what the big deal is. When the post is removed, you're notified via a message that links to the removed comment. You can still view it, so just copy your old comment, then paste it into a new comment with the required "answer:" in front of it. It takes five seconds to do.
50
ask
u23yrt
The process for replies to serious questions on r/ask requires commenters to begin a comment reply with `answer:`. Any replies that don't begin with that syntax are removed. This is a very blunt solution to the problem of redditors' attempts to be hilarious in comments where the OP has requested only serious discussion. This has been a source of frustration for many of you who are posting well-intentioned replies that are being auto removed for not following the required syntax. Be advised that we have heard your feedback and are taking it into consideration to determine how we can best improve this process for the entire r/ask community. We hope to strike a better balance between removing joke/non-serious replies to threads with the `serious replies only` flair and permitting the actual serious replies. We've heard you in modmail and in the comments and will return soon with an announcement on what direction we'll take. Whatever form the new process takes, it will likely involve a greater role for user reporting so please remember that user reports are the fastest and best way to inform the moderator team of any issues with posts, comments, or users in the community. Thank you for your feedback on this issue and for your continued participation on r/ask. -r/ask mod team
Answer: about fucking time. Making it inconvenient to answer a question someone is seriously asking is a stupid exploitation of the control the mods have. People are gonna troll, no reason to punish us all.
30
ask
u28t3h
Say I have a enum like the following: enum MyEnum{ Foo, Bar, Baz, } I then have a vector like so: let v = vec![MyEnum::Foo, MyEnum::Foo, MyEnum::Bar]; I now want to know how many instances of each variant appear in the vector. Basic questions: 1. what is the most appropriate data structure to represent the mapping from variants to their counts? 2. how do I go about computing these counts in an efficient way? I thought to implement this using a `HashMap::<MyEnum,usize>`, but I really don't know if that's the right way to do it. Aside from these (admittedly very basic) questions, I also don't understand how I can go about identifying how many counts I even require because it's not clear to me how to identify the number of variants I have in the first place. I know that there is a "variants\_count" function possibly coming in some future rust release, but it seems not to be available yet. Note that I am aware that I can also attach data to variants of the enum when I define, and thought that I could perhaps do this that way (somehow). However, my vector `v` in this example will eventually come via an external C application, and I am not clear how much harder it would be to define compatible types if I overcomplicate my enum definition.
Check out [Itertools::counts](https://docs.rs/itertools/latest/itertools/trait.Itertools.html#method.counts) to get a `Hashmap::<MyEnum, usize>`. This map will only contain keys where the count is greater than 0, so "missing" enums will not be present. That might mean needing to deal with `None` from a `get(MyEnum::Variant)` Since the vector comes from outside your code, you are left with counting the items yourself. There are more manual ways of doing so, but they all end up involving iterating over the vector.
120
LearnRust
u28t3h
Say I have a enum like the following: enum MyEnum{ Foo, Bar, Baz, } I then have a vector like so: let v = vec![MyEnum::Foo, MyEnum::Foo, MyEnum::Bar]; I now want to know how many instances of each variant appear in the vector. Basic questions: 1. what is the most appropriate data structure to represent the mapping from variants to their counts? 2. how do I go about computing these counts in an efficient way? I thought to implement this using a `HashMap::<MyEnum,usize>`, but I really don't know if that's the right way to do it. Aside from these (admittedly very basic) questions, I also don't understand how I can go about identifying how many counts I even require because it's not clear to me how to identify the number of variants I have in the first place. I know that there is a "variants\_count" function possibly coming in some future rust release, but it seems not to be available yet. Note that I am aware that I can also attach data to variants of the enum when I define, and thought that I could perhaps do this that way (somehow). However, my vector `v` in this example will eventually come via an external C application, and I am not clear how much harder it would be to define compatible types if I overcomplicate my enum definition.
So there are two ways to go about this. One is to use, as TopGunSnake suggested, the itertools crate to do the work. And this is perfectly legitimate. Now, let's consider some alternative approaches to the problem that are instructive for ways to approach this. We can do the hash map addition manually with something like this: let mut counts = HashMap::new(); v.iter().for_each( |val| { counts.entry(val) .and_modify(|count| { *count += 1 }) .or_insert(1); } ); println!("{counts:?}") You also will need to add #[derive(Eq, PartialEq, Hash, Debug)] to your declaration of `MyEnum` so that you can do the appropriate hashing and equality operations on `MyEnum`.¹ If this is performance sensitive code, you may find that the default hash algorithm, which goes to some lengths to be resilient against DoS attacks is slow for your needs. Now for some dark magic as an alternative approach, if we have no fields in the values for MyEnum, we have access to the discriminant, which is just the numeric index (starting at zero) of the enum item. With this, we can construct a vec of counts as follows: let mut counts = Vec::new(); v.iter().for_each( |&val| { let idx = val as usize; if counts.len() <= idx { // Make sure there are enough empty entries at the end of the // vec to let us accesswhere we want to be counts.append(&mut vec!(0;idx - counts.len() + 1)) } counts[idx] += 1; } ); println!("{counts:?}"); Here, we need to derive `Copy` and `Clone` for the code to work so that we can move the value out of a reference for the conversion to `usize`. ​ ⸻ 1. JVM people will be well aware of the need to implement `.equals()` and `.hashCode()` any time you want to use a custom object as the index to a hash map.
30
LearnRust
u2l8z7
Hi there! I'm writing some physics code and I'd like to reserve the ability to use arbitrary precision down the road, so I wanted to use generics. Let's say I have a function like this: ``` // Speed of light in vacuum. const C: f32 = 299792458.0; // Compute the Lorentz Factor for a given acceleration at time t. pub fn lorentz<T: num_traits::float::Float>(a: T, t: T) -> T { let x = (a * t) / (C as T); T::sqrt(x) } ``` Predictably, this won't build, because I can't cast to type T. After Googling around, I'm stumped. There is something called constant generics, but it seems to be closer to C++ template parameters. What would be the idiomatic way of doing something like this?
Preface with **I know nothing about this crate**. And I'm as useful as a bag of bricks when it comes to math. I found that you can cast and use it. First generic is just input type. Second is output. num_traits::cast::<_, T>(C).unwrap() Which works. Another thing I noticed though. C is being messed up (don't know the word right now it's 4 am.) With C as u32 it stayed the same. This is just me using println. Once in main and once in lorentz fn with cast value. const f32: 299792458.0 println C: 299792450 println Cast of C: 299792448.0 const u32: 299792458 println Val: 299792458 println Cast of Val: 299792458.0 **I don't know if someone else wants to chime in with some more info. I would appreciate it.** Anyways bedtime for me.
80
LearnRust
u2l8z7
Hi there! I'm writing some physics code and I'd like to reserve the ability to use arbitrary precision down the road, so I wanted to use generics. Let's say I have a function like this: ``` // Speed of light in vacuum. const C: f32 = 299792458.0; // Compute the Lorentz Factor for a given acceleration at time t. pub fn lorentz<T: num_traits::float::Float>(a: T, t: T) -> T { let x = (a * t) / (C as T); T::sqrt(x) } ``` Predictably, this won't build, because I can't cast to type T. After Googling around, I'm stumped. There is something called constant generics, but it seems to be closer to C++ template parameters. What would be the idiomatic way of doing something like this?
You can use num_traits::NumCast `T::from(C).unwrap()`, which is required by Float.
40
LearnRust
u3kfph
Why is this acept in Rust for i in &v { println!("{}", i); } but this isn't? for i in &my_numbers{ println!("{}",my_numbers[i]);   } could someone help me
In the second case 'i' is your enumerator. Think of a vector containing [1,4,8]. First case you iter through the elements 1 4 and 8. In the second case you iter through the 1st, 4th and 8th element of your vector.
140
LearnRust
u3kfph
Why is this acept in Rust for i in &v { println!("{}", i); } but this isn't? for i in &my_numbers{ println!("{}",my_numbers[i]);   } could someone help me
When you say for item in &collection You're telling Rust to go through the `elements` in collection and borrow them in `item`. So your first example works because it's just dealing with the values in your vector. But in the second case, you're trying to use the value as an index. There are two problems here. One is that `i` is going to be the wrong type. You need a `usize` to index into the `vec`, and you have instead a reference to some number. Changing your index to `my_numbers[*i]` will allow rust to infer that the numbers in your `vec` are `usize` (unless you've explicitly stated otherwise), but this is almost certainly not what you want since it's unlikely that you really want to have the values in a `vec` refer to other locations in that same `vec`.¹ More likely, if you want to iterate by index, you could do something like: for i in 0..my_numbers.len() which will iterate over the valid indices on `my_numbers`. As an added bonus, you no longer need the deref `*` so you would be able to just write `my_numbers[i]` when referring to the elements in `my_numbers`. ⸻ 1. Although not impossible, I can see using this as a means of representing a directed graph
80
LearnRust
u3snaa
Is something wrong with my IDE or the Rust extension? This function returns a Result.
The `? ` operator only works when the caller also returns a Result of the same error type or a error type where From/Into is implemented. You can actually change the signature of main to `fn main() -> Result<(), YourError> {} ` as long as YourError implements core::fmt::Display.
460
LearnRust
u3snaa
Is something wrong with my IDE or the Rust extension? This function returns a Result.
FYI: it seems you ran `cargo run` in your terminal, and it displayed the error message. This means the compiler couldn't compile your code and it should have nothing to do with your IDE or Rust analyser :)
100
LearnRust
u3snaa
Is something wrong with my IDE or the Rust extension? This function returns a Result.
main() should return a Result or Option
30
LearnRust
u4s77q
Hi guys, What do you use to manage your build pipelines? Specifically here are some things that I need to do per build: \- separate cargo.toml settings, for example to change LTO settings \- copying result files after the build Right now im using simple shell scripts to do it. I use Webpack a lot in other projects, and commands like 'npm run dev' allow me to do a bunch of stuff during builds. I'd love something similar for my rust project
Maybe [profiles](https://doc.rust-lang.org/cargo/reference/profiles.html) would be a nicer solution? I’m not entirely sure what you’re looking for, but maybe [zero2prod](https://www.zero2prod.com/) would also be of use.
50
LearnRust
u4xjel
Suppose I have a method which opens the file. Since it may fails, it should returns **Result**, right? fn create_file(file_name: &str) -> Result<File, &'static str> { let file = OpenOptions::new() .write(true) .create(true) .open(file_name) .unwrap_or_else(|error| { // or more specific / non-panic error handling panic!("Problem creating the file: {:?}", error); }); Ok(file) } But then, at place of method execution, I have to make basically the same error handling/checking: ... let mut file = create_file(FILE_NAME).expect("Unable to create new file"); ... Or I could jut **unwrap** since I have error handling within **open\_file** ? let mut file = create_file(FILE_NAME).unwrap(); How to do it in a right way?
Okay, let's take a simple example where, depending on some numeric input, we cause different errors to occur and propagate up a contrived call-chain: use std::error::Error; use std::fmt; use std::io; // our generic result type that can handle any error type GenResult<T> = Result<T, Box<dyn Error + 'static + Send + Sync>>; // our first error type #[derive(Debug)] struct ErrorOne { message: String, } impl ErrorOne { pub fn new(message: &str) -> Self { ErrorOne { message: message.to_string(), } } } impl fmt::Display for ErrorOne { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}", self.message) } } impl Error for ErrorOne {} // our second error type #[derive(Debug)] struct ErrorTwo { message: String, } impl ErrorTwo { pub fn new(message: &str) -> Self { ErrorTwo { message: message.to_string(), } } } impl fmt::Display for ErrorTwo { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}", self.message) } } impl Error for ErrorTwo {} // helper to get input fn get_num() -> i32 { let mut input = String::new(); io::stdin() .read_line(&mut input) .expect("failed to read input"); input.trim().parse::<i32>().unwrap() } // the main man fn main() { let option = get_num(); // need to do the check only here // and not in any of the lower-levels match foo(option) { Err(e) => println!("{}", e), Ok(val) => println!("{}", val), } } // foo calls bar (which can fail) fn foo(input: i32) -> GenResult<i32> { Ok(bar(input)?) } // bar calls baz (which can fail) and quux (which can fail) fn bar(input: i32) -> GenResult<i32> { baz(input)?; Ok(quux(input)?) } fn baz(input: i32) -> GenResult<()> { if input == 1 { Err(Box::new(ErrorOne::new("baz caused an issue"))) } else { Ok(()) } } // quux call foobar (which can fail) fn quux(input: i32) -> GenResult<i32> { Ok(foobar(input)?) } fn foobar(input: i32) -> GenResult<i32> { if input == 2 { Err(Box::new(ErrorTwo::new("foobar caused an error"))) } else { Ok(100) } } Running it: ~/dev/playground/result-demo:$ cargo run --release 0 100 ~/dev/playground/result-demo:$ cargo run --release 1 baz caused an issue ~/dev/playground/result-demo:$ cargo run --release 2 foobar caused an error So, in this simple (albeit contrived) example, we can start seeing the benefits of not just the `Result` type, but also the `?` operator. Have a look at the annotated code above and see if it makes sense to you. tl;dr - In your specific case, 1. Imagine that the`create_file` API is being called by several levels of clients (as in the example shown above), and you *do not* wish to have to pattern-match at each level, or indeed `unwrap` and then propagate at each level. Then having `create_file` return a `Result` starts making sense. 2. Imagine then a case like `bar` in the example above where you have multiple steps within a specific function that can potentially fail. In this case, it's even more useful using the `?` operator in conjunction with (and indeed you have to) using some sort of `Result` as the return type of the function. The alternative would be a veritable mass of spaghetti code. So, basically something like so: fn some_function() -> Result<SomeType, SomeError> { can_fail1()?; can_fail2()?; ... can_failN()?; Ok(return_this_calls_value()?) } Conclusion - yes, use `Result` unless you're absolutely sure that something is only called at most one level deep, or is infallible. It also helps with code documentation.
80
LearnRust
u4xjel
Suppose I have a method which opens the file. Since it may fails, it should returns **Result**, right? fn create_file(file_name: &str) -> Result<File, &'static str> { let file = OpenOptions::new() .write(true) .create(true) .open(file_name) .unwrap_or_else(|error| { // or more specific / non-panic error handling panic!("Problem creating the file: {:?}", error); }); Ok(file) } But then, at place of method execution, I have to make basically the same error handling/checking: ... let mut file = create_file(FILE_NAME).expect("Unable to create new file"); ... Or I could jut **unwrap** since I have error handling within **open\_file** ? let mut file = create_file(FILE_NAME).unwrap(); How to do it in a right way?
Since your code will panic within the `create_file` function it doesn't make sense to return a `Result`. The `Err` will never actually get returned. You need to handle the error where it is best suited, either inside the function or at the function call. I generally prefer to handle it outside the function (at the call).
70
LearnRust
u50cz8
I am trying to implement some vectorized math operations and struggling a bit with borrow checking when computing on vectors in place. As an example, say I want to implement a "times two" operation on a vector. I implement a trait for vectors like this: pub trait TimesTwo { fn timestwo(&mut self, y: &Self); } impl TimesTwo for [f64] { fn timestwo(&mut self, y: &[f64]){ self.iter_mut().zip(y).for_each(|(x,y)| *x = 2. * y); } } This is fine if want to do this: let mut x = vec![0.,0.,0.]; let y = vec![4.,5.,6.]; x.timestwo(&y); It doesn't work though if want `x` to perform this operation on itself. In other words, the borrow checker won't allow this: x.timestwo(&self); The only options I can see are either : * Add a separate function like `fn timestwo_self(&mut self);` and use that whenever I want to take `self` as an argument. * **only** implement the function to operate elementwise on `self`, and then copy from `y` into `x`before calling this function. Neither of these options seems ideal. The first way means I will have twice as many functions to maintain. The second way means I only have one function to write, but I effectively end up with two loops; one for the copy, and one for the operation itself. I really want to avoid this since it is for a scientific computing application. Is there some other way?
Write your modifier as a separate function that takes an element and returns an updated element. Implement a method on your collection to apply modifier to each of its elements. When using with different collections, you can just use that same modifier via iterators. As a result, you only need to implement each of your modifiers once. trait InPlaceOperations { fn modify_with(&mut self, modifier: impl fn(f64) -> f64); fn populate_from(&mut self, from: impl Iterator<Item = f64>); } impl InPlaceOperations for Vec<f64> { fn modify_with(&mut self, modifier: impl fn(f64) -> f64) { for item in self { *item = modifier(item) } } fn populate_from(&mut self, from: impl Iterator<Item = f64>) { self.iter_mut.zip(from).for_each(|(x, y)| *x = y) } } fn times_two(input: f64) -> f64 { input * 2 } fn divide_by_two(input: f64) -> f64 { // … } x.modify(times_two); x.populate_from(y.iter().map(times_two));
30
LearnRust
u590hi
Hello guys.Basically I just want update existing data in existing file (lets say there is some vector with strings). Am I doing it wrong?:Is there any way to read data and write from the same file (instance?) using **OpenOptions**? Suppose I have a code like this: let mut file_to_read_in = OpenOptions::new() .write(true) .truncate(true) .open(FILE_NAME) .expect("Could not open file"); If I have **truncate** flag, my file will be cleared before I'll take it. I can solve my problem with having different files options instances (instances I suppose...? 🤔) with code like this: let file_to_read_data_first = File::open(FILE_NAME).expect("Could not open file"); let mut file_to_read_in = OpenOptions::new() .write(true) .truncate(true) .open(FILE_NAME) .expect("Could not open file"); where I firstly read the data from **file\_to\_read\_data\_first**, update that data and then write to **file\_to\_read\_in**. But it doesn't look good and right.
I took a glance at the documentation of File struct. If u understand it correctly, you can open the file for read and write, read the contents and then "rewind" that file to the beginning for writing. Here are docs for the rewind function: https://doc.rust-lang.org/std/io/trait.Seek.html#method.rewind (File implements Seek) Take a look into the example - there, they're using it in the opposite way, first writing to file, rewinding and then reading from the beginning. You might also want to use `set_len` function to clear the file before writing (because when you just rewind before writing, and the new data takes less bytes, I assume the leftovers from the old contents will be left there right after your new data, possibly making your file corrupt for next read) https://doc.rust-lang.org/std/fs/struct.File.html#method.set_len Keep in mind I'm giving you these advice just after reading the documentation, I haven't used them at all, so test it properly :)
70
LearnRust
u5i2r5
Reading the rust book I have stumbled upon this. In the book it's said that `join()` blocks the main thread until associated thread finishes it work. Now, kindly look at this code: ```rust 1 | use std::thread; 2 | 3 | fn main() { 4 | let s = String::from("hi"); 5 | 6 | let r1 = &s; 7 | 8 | let handle = thread::spawn(move || { 9 | println!("{}", r1); 10| }); 11| 12| handle.join().unwrap(); 13| } ``` In theory, as I am doing `handle.join()`, `s` should be dropped after the spawned thread finishes its work. But the error says: ``` let mut s: String Go to String `s` does not live long enough borrowed value does not live long enough (rustcE0597) main.rs(13, 1): `s` dropped here while still borrowed main.rs(8, 18): argument requires that `s` is borrowed for `'static` ``` So the error is stating that s is dropped at the end of scope while I am trying to use it in another thread. Am I understanding `join()` wrong?
The issue is that the compiler doesn't understand that you join the thread right after, while the borrowed value is still alive. All it knows is that a new thread can only borrow values that can live as long as 'static does. You can try `crossbeam::scoped` API that has a workaround allowing you to reference variables from the main thread
70
LearnRust
u5qewx
PS: Sorry about the horrible formatting in the code block, I tried my best 😅 Hello Guys, I am currently writing some code where I am handling a struct, something like the following struct(only with many more fields, but the same type): struct PyData{ val1: usize, val2: usize, val3: usize } I'd like to convert this struct into a HashMap since I using the PyO3 framework to make this a Python library, but I am currently ending up with this ugly thing(with PyError being a custom error type : impl PyData{ fn get_data(&mut self) -> Result<HashMap<&'static str, usize>, PyError>{ let data : self.get_data(); // Method to fetch the data match data { Ok(data) => { Ok(HashMap::from([ ("val1", data.val1) ("val2", data.val2) ("val3", data.val3) ])) } Err(_) => Err(PyError), } } } Is there a better way to do this, instead of my current method? The struct I am using has 15 fields, and will grow in the future, so I would really like to avoid typing the fields in manually if I can.
I think a good solution to this would be macros. Eg: impl_py_data!(struct PyData{ …fields… }) Here’s an intro to them: https://doc.rust-lang.org/rust-by-example/macros.html Hopes this helps.:). Sorry for bad formatting
40
LearnRust
u5qewx
PS: Sorry about the horrible formatting in the code block, I tried my best 😅 Hello Guys, I am currently writing some code where I am handling a struct, something like the following struct(only with many more fields, but the same type): struct PyData{ val1: usize, val2: usize, val3: usize } I'd like to convert this struct into a HashMap since I using the PyO3 framework to make this a Python library, but I am currently ending up with this ugly thing(with PyError being a custom error type : impl PyData{ fn get_data(&mut self) -> Result<HashMap<&'static str, usize>, PyError>{ let data : self.get_data(); // Method to fetch the data match data { Ok(data) => { Ok(HashMap::from([ ("val1", data.val1) ("val2", data.val2) ("val3", data.val3) ])) } Err(_) => Err(PyError), } } } Is there a better way to do this, instead of my current method? The struct I am using has 15 fields, and will grow in the future, so I would really like to avoid typing the fields in manually if I can.
Maybe you can do some magic with traits and serde, since you're kinda serealizing the struct?
30
LearnRust
u68jb0
I'm writing a program to interact with some [IOT lighting](https://us.yeelight.com/shop/yeelight-led-smart-bulb-w3-multicolor/) over TCP. The lights send status updates over this connection and you can send actions back to them. I want to be able to know if the connection is dropped, say in the case where they are hard powered off (by turning the light switch off). However, when I try to write to them after powering off the `write` call is successful and returns the correct number of bytes written. Why is this case? And how can I figure out if they're hard powered off? I could send a message over the connection and set a timeout for a response, but wondering if there's something else I'm missing? Happens on both mac OS and Linux. Code here: https://github.com/haydenwoodhead/bulb/blob/ff881ccb273ac278bbd8732ef7805e6001b9ddeb/src/server.rs#L192
Because a powered off client wont be able to close the stream and inform the other end. You get the same if you kill the client process instead of closing the connection. Thus, a *connection* timeout is a good recourse, as the socket waits for an acknowledgment. The mechanism is same for both ways, if the server was abnormally terminated/killed, or the ethernet unplugged, etc. Edit: Also you are using Tokio, an async library, which means the thread wont block for a timeout before proceeding. Others used [this library](https://crates.io/crates/tokio-io-timeout)
60
LearnRust
u68jb0
I'm writing a program to interact with some [IOT lighting](https://us.yeelight.com/shop/yeelight-led-smart-bulb-w3-multicolor/) over TCP. The lights send status updates over this connection and you can send actions back to them. I want to be able to know if the connection is dropped, say in the case where they are hard powered off (by turning the light switch off). However, when I try to write to them after powering off the `write` call is successful and returns the correct number of bytes written. Why is this case? And how can I figure out if they're hard powered off? I could send a message over the connection and set a timeout for a response, but wondering if there's something else I'm missing? Happens on both mac OS and Linux. Code here: https://github.com/haydenwoodhead/bulb/blob/ff881ccb273ac278bbd8732ef7805e6001b9ddeb/src/server.rs#L192
That's what TCP keepalive is for. [https://tldp.org/HOWTO/html\_single/TCP-Keepalive-HOWTO/](https://tldp.org/HOWTO/html_single/TCP-Keepalive-HOWTO/) If your operating system does support TCP keepalive, you can send keepalive messages at the application layer (see for example section 4.4 in the BGP specification https://datatracker.ietf.org/doc/html/rfc4271)
50
LearnRust
u6ffx4
Why not just panic with `index out of bounds` in case of e.g. -1?
Indexing uses the [Index](https://doc.rust-lang.org/std/ops/trait.Index.html) trait, which in the case of `Vec` is implemented for `usize`. In theory it could be implemented for other types as well, for example an implementation of `Index<isize>` could behave as you described. I'd actually like to see python-like indexing with negative numbers that index from the end of the vector, but it's probably not useful enough to be implemented.
90
LearnRust
u6ffx4
Why not just panic with `index out of bounds` in case of e.g. -1?
I’m fairly sure it’s because usize matches the size of the addresses that the cpu/mcu uses to find the content of each cell of the vector. A vec of 100 elements would start at a point in memory that is usize and then add the size of an element to get the position of the next element. Everyone please correct me if I said that poorly. You would have to convert what ever you used to get the element to usize eventually. Element memory address = index * size of + start, all usize is just the most efficient way.
70
LearnRust
u6sqzl
From what I've read it is not clear to me if there is a full web framework for Rust like rails or Phoenix. It appears to me that Rocket or Actix are closest to this but I'm not sure. Is there anything like a full web framework for Rust yet? I mean something where you get html templating with forms having csrf security and other stuff just work (even if there is more typing than rails), db management, css/js asset management, sessions (with cookies), etc. Having to type more than rails is fine it just needs to actually work without having to think about security holes like csrf. What is the closest thing to this today?
I think these 2 posts from this sub can be helpful: * [Rust on Nails - A full stack architecture for Rust web applications](https://redd.it/u2ny6e) * [A Rust server / frontend setup like it's 2022 (with axum and yew)](https://redd.it/tvqlhd)
110
LearnRust
u6zkud
Hi, quick question, I have a situation where I need to make sure that the result of an operation is above 0, since it will be assigned to a usize. Is there a way to do this without casting everything to isize first? let a:usize = 3; let b:usize = 5; let res:usize = a - b; // panic. how to test?
If the result is negative this code will only panic in debug mode in release mode it will silently wrap (i think). You can use checked_sub/saturating_sub/wrapping_sub to ensure it's valid. https://doc.rust-lang.org/stable/std/primitive.usize.html#method.checked_sub
230
LearnRust
u6zkud
Hi, quick question, I have a situation where I need to make sure that the result of an operation is above 0, since it will be assigned to a usize. Is there a way to do this without casting everything to isize first? let a:usize = 3; let b:usize = 5; let res:usize = a - b; // panic. how to test?
`checked_sub` is one way. `saturating_sub` could also work if you want the result to be zero in the overflow case. If you want the magnitude of the difference, you can use `abs_diff`. (https://doc.rust-lang.org/std/primitive.usize.html) If you want the magnitude of the difference you could check which is smaller and swap them if necessary, if you'd prefer to do it yourself for whatever reason.
50
LearnRust
u7cmof
I want to be able to change the desktop volume, is there any crate for this? I had a look through [crates.io](https://crates.io) and couldn't find anything, and also had a look at the linux crates but there are so many. Ideally a cross-OS abstraction, but failing that a Linux specific solution.
you can just write your own cross-platform wrapper. there is [waveOutSetVolume](https://docs.microsoft.com/en-us/windows/win32/api/mmeapi/nf-mmeapi-waveoutsetvolume) for windows which windows-rs crate has the bindings for or you can always link Winmm.lib yourself. not sure about linux.
40
LearnRust
u7kyyz
```rust // fn weighted_sum(input: &[f32], weights: &[&[f32]]) { ...... } //above function wont accept &[&[0.1, 0.2, 0.5], &[0.6, 0.3, 0.7]] as an arguments(weights), because "mismatched types", but it accepts &[5.2, 0.1, 0.3] as argument(input) even more mindblowing is the error says it expect &[&[f32]] but it got &[&[f32;3];3] i could use a vec here but why doesnt this work ? thanks in advance ```
Generally Rust will deref arrays / vecs passed by reference if the function accepts a slice, but it won't do this recursively. You can use the .as_ref() method to convert the inner arrays to slices.
60
LearnRust
u7kyyz
```rust // fn weighted_sum(input: &[f32], weights: &[&[f32]]) { ...... } //above function wont accept &[&[0.1, 0.2, 0.5], &[0.6, 0.3, 0.7]] as an arguments(weights), because "mismatched types", but it accepts &[5.2, 0.1, 0.3] as argument(input) even more mindblowing is the error says it expect &[&[f32]] but it got &[&[f32;3];3] i could use a vec here but why doesnt this work ? thanks in advance ```
Are you sure you provided the error correctly? This works on the [rust playground](https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=bfeddafd31abc93d293d94fe9f0803ff). Or am I misreading the post?
30
LearnRust
u88v0d
I am new to Rust coming from C++ so I was wondering if there was an easy way to open a file and get the integers to store in an array. I don't want to convert to string first, I would like to just read it in directly. The text file format is know and will consist of 9 lines of 9 numbers deperated bt space. I appreciate any help.
There is no "converting to a string first", as the file contents is already in a string format. Note how the byte-size of a text file containing `4294967295` is 10 bytes despite the fact that 2\^32-1 easily fits into 4 bytes and even standard machine words are 8 bytes. This is because data in text editors (human readable data) is an array of at least one byte per character, aka a string. The reason why you don't have to manually convert it in C++, is because this conversion is done implicitly (which causes it's own problems). So instead read the whole file into a string, `split_whitespace` and `collect` into a `Vec<&str>`, then use the method `parse::<u64>()` on the elements to convert the strs into u64s. If you have a guarantee of the size of the integers and properties of the file then you can write a faster implementation, but the implementation above will work in the general case.
190
LearnRust
u9ftdk
Hi, I'm about to finish reading the official Rust lang book and I'm interested in creating a CLI app as my next phase of learning Rust. I want to create something that will be really useful in my learning process, a medium or big project where I can practice most of Rust's features. Something the community need or a popular app that has no Rust counterpart will be great!
Something like `jq` in rust could be fun.
70
LearnRust
u9ftdk
Hi, I'm about to finish reading the official Rust lang book and I'm interested in creating a CLI app as my next phase of learning Rust. I want to create something that will be really useful in my learning process, a medium or big project where I can practice most of Rust's features. Something the community need or a popular app that has no Rust counterpart will be great!
I had the same "problem" - I've wanted to build some CLI to give Rust a first try on some project, but I had no idea what to do. Lately I happened to be in a situation that I had to do a lot of manual work on some repositories (github, bitbucket, setting up CI configuration). So I did create CLI to automate some work for me, it was using both Bitbucket and GitHub api, used git2 for managing repositories locally and it was parsing some ci configuration files (yaml) for CI. Later on i shared it with my team so when there is a need to do some of these actions again, we already have a tool for it :) The point is, do something for yourself first, i think this will be a better way of learning than doing something that you're not really interested in using or passionate about (leave that stuff for work 😅). So I would suggest thinking of things you can automate for yourself, either personal or work-related things, but something that you care about - this will keep you looking for answers as you'd want to finish this for yourself. Good luck 🤞
50
LearnRust
ua8tla
What's the better way to write this pub fn first_n_words(text: &str, n: usize) -> String { let words = text.split_whitespace().collect::<Vec<&str>>(); words[..words.len().min(n)].join(" ") } I don't actually expect the input to ever be large enough to make a difference, but for the sake of learning, let's pretend it could be large.
Since split_whitespace() returns a SplitWhitespace, and that type implements Iterator, take a look at the take() function on Iterator. You’d put a split_whitespace().take(n).collect() There’s a function in the itertools crate, I think, that can also join elements of an Iterator directly without having to collect them first, as well.
230
LearnRust
ua8tla
What's the better way to write this pub fn first_n_words(text: &str, n: usize) -> String { let words = text.split_whitespace().collect::<Vec<&str>>(); words[..words.len().min(n)].join(" ") } I don't actually expect the input to ever be large enough to make a difference, but for the sake of learning, let's pretend it could be large.
As u/ajf said, you want the [`take` method of `Iterator`](https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.take). For the function here, searching for the index of the `n`th word delimiter and then doing `&text[..index]` and returning that string slice _could_ be better.
60
LearnRust
uax3l9
Salutations, I am working on a program that I think would benefit from being able to run from inside a python program. I would like to be able to represent my enums and structs and things as Python objects, I'd like to be able to call my Rust functions from inside Python. My googeling led me to [this blogpost](https://bheisler.github.io/post/calling-rust-in-python/), but it was published five years ago and things seem to move quickly in Rust land. So is that information still up-to-date? It looks like I somehow have to compile the Rust binary as a shared object, and then in Python-land, create a wrapper around the thing using ctypes or something similar. Does anyone here have any experience with this kind of thing?
You can check out [PyO3](https://pyo3.rs/), which is the library I see most people using both ways (calling rust from python, or python from rust).
160
LearnRust
uax3l9
Salutations, I am working on a program that I think would benefit from being able to run from inside a python program. I would like to be able to represent my enums and structs and things as Python objects, I'd like to be able to call my Rust functions from inside Python. My googeling led me to [this blogpost](https://bheisler.github.io/post/calling-rust-in-python/), but it was published five years ago and things seem to move quickly in Rust land. So is that information still up-to-date? It looks like I somehow have to compile the Rust binary as a shared object, and then in Python-land, create a wrapper around the thing using ctypes or something similar. Does anyone here have any experience with this kind of thing?
I heartily endorse pyo3. I recently wrote a project for running encrypted python code for work. It's basically a command line app that connects to a license server to get a secret key, and uses the key to decrypt an encrypted python script, and then runs it, but also provides a few functions to the python context that the script can use. So there's a rust program calling into python, which then imports a module that was created by the rust program that started the python script to begin with, and I was able to do all that without too much difficulty, by following the pyo3 documentation, and experimenting a little bit. It's quite powerful, and once you wrap your mind around the 'py lifetime, and the implicit conversions between python and rust types, pretty straightforward to do what you want. The only thing I couldn't figure out was how to create a python class in rust that subclasses a custom class written in Python, so I opted to make the python class accept a callback in its constructor instead to inject functionality from rust. It wasn't the most elegant, but it did the trick.
30
LearnRust
uax3l9
Salutations, I am working on a program that I think would benefit from being able to run from inside a python program. I would like to be able to represent my enums and structs and things as Python objects, I'd like to be able to call my Rust functions from inside Python. My googeling led me to [this blogpost](https://bheisler.github.io/post/calling-rust-in-python/), but it was published five years ago and things seem to move quickly in Rust land. So is that information still up-to-date? It looks like I somehow have to compile the Rust binary as a shared object, and then in Python-land, create a wrapper around the thing using ctypes or something similar. Does anyone here have any experience with this kind of thing?
Second the recommendations for pyo3 and maturin, have had great experiences with those. You don't have to use ctypes; it depends on the structure of your project. Most of the time I'll write something that will compile straight to a python library or write a core rust crate and then a python bindings crate that depends on the first and basically creates a clean interface to the rust code the form of python modules, classes, functions, and exceptions.
30
LearnRust
ubwkuy
Hello! I want to understand how model checkers work, as I am planning to implement one. Also what other topics should I know before diving into model checkers?
Are you asking about Formal Methods model checkers?
30
AskComputerScience
ucany7
I am stuck between either a MacBook pro 13 in and the Air. I could buy the 16GB memory Air for less the amount of the Pro (8GB). I've watched some reviews and they say that there are totally little to no difference between the 2.
The MacBook Air should be very similar in performance to the 13“ Pro if both have the m1
50
AskComputerScience
ucany7
I am stuck between either a MacBook pro 13 in and the Air. I could buy the 16GB memory Air for less the amount of the Pro (8GB). I've watched some reviews and they say that there are totally little to no difference between the 2.
Literally any one. I use a Thinkpad x201 that's over 10 years old and is perfectly fine for running ides and doing experiments
40
AskComputerScience
ucany7
I am stuck between either a MacBook pro 13 in and the Air. I could buy the 16GB memory Air for less the amount of the Pro (8GB). I've watched some reviews and they say that there are totally little to no difference between the 2.
/r/SuggestALaptop/
30
AskComputerScience
ucc9tv
Hello all, As the title suggest, I am looking for some good books to pickup Rust. I have read some blogs out there that suggest: The Rust Programming Language (Covers Rust 2018) by Steve Klabnik and Carol Nichols My concern is that the book says that it covers Rust 2018. After some more searching, I discovered that meant rust 1.31.x. However, Rust is now on 1.60.0. I know that Rust changes pretty frequently so my concern is the relevancy of the book and what all has changed since. Hoping that the community can spread some light on this for me. Thanks in advance.
IIRC, the book's been updated for 2021 edition i.e >=1.58
150
LearnRust
ucc9tv
Hello all, As the title suggest, I am looking for some good books to pickup Rust. I have read some blogs out there that suggest: The Rust Programming Language (Covers Rust 2018) by Steve Klabnik and Carol Nichols My concern is that the book says that it covers Rust 2018. After some more searching, I discovered that meant rust 1.31.x. However, Rust is now on 1.60.0. I know that Rust changes pretty frequently so my concern is the relevancy of the book and what all has changed since. Hoping that the community can spread some light on this for me. Thanks in advance.
I enjoyed reading: [Programming Rust: Fast, Safe Systems Development ](https://www.amazon.com/Programming-Rust-Fast-Systems-Development/dp/1492052590) covers Rust 1.56.0 also has some interesting mini-projects where the authors implement concepts from Rust to show the reader how they work.
140
LearnRust
ucc9tv
Hello all, As the title suggest, I am looking for some good books to pickup Rust. I have read some blogs out there that suggest: The Rust Programming Language (Covers Rust 2018) by Steve Klabnik and Carol Nichols My concern is that the book says that it covers Rust 2018. After some more searching, I discovered that meant rust 1.31.x. However, Rust is now on 1.60.0. I know that Rust changes pretty frequently so my concern is the relevancy of the book and what all has changed since. Hoping that the community can spread some light on this for me. Thanks in advance.
**Not books, but the best resources I've found for learning rust.** [Learning Rust! Going through the Rust Language book (Video series)](https://youtube.com/playlist?list=PLSbgTZYkscaoV8me47mKqSM6BBSZ73El6) [Learning Rust! Exercism.org Rust Track (Video series)](https://youtube.com/playlist?list=PLSbgTZYkscappmMh-4I6Mrro03on9RWgT) [The Rust Lang Book (Video series)](https://youtube.com/playlist?list=PLai5B987bZ9CoVR-QEIN9foz4QCJ0H2Y8) [RUST PROGRAMMING TUTORIALS (Video series)](https://youtube.com/playlist?list=PLVvjrrRCBy2JSHf9tGxGKJ-bYAN_uDCUL) [Learning rust with exercism (Video Series)](https://youtube.com/playlist?list=PLBAZWBMYeVYjK_XjNskASXldA2VJR1G04) [The Rust Programming Language Book](https://doc.rust-lang.org/book/title-page.html) [My explanation of the main concepts in Rust](https://gist.github.com/DarinM223/e7237114cfdcf3644f90) [Rust By Example](https://doc.rust-lang.org/book/title-page.html) [Learning Rust](https://learning-rust.github.io/) [Educative](https://www.educative.io/courses/learn-rust-from-scratch) [Tour of Rust](https://tourofrust.com/index.html) [A half-hour to learn Rust](https://fasterthanli.me/articles/a-half-hour-to-learn-rust) **Practice** [Exercism](https://exercism.org/tracks/rust) [Code Wars](https://www.codewars.com/kata/search/rust)
90
LearnRust
ucfu5e
Join The Comunity;) Ip:85.190.160.217:17000 Discord:[https://discord.gg/5bvKEZz5g7](https://discord.gg/5bvKEZz5g7)
Is it memory safe?
70
LearnRust
ucqqjy
...now that MIPS technologies jumped to the RISC-V bandwagon?
I don't, but I bet colleges will still be using the current instruction set in 2100.
50
AskComputerScience
ucvk1m
Hello everyone! I’m an EE working with all EE’s. I’ve inherited a major monstrosity of a program (Python). There are methods that call methods in classes that inherit and use attributes from another classes which have methods that call other modules…etc etc. I tried to track down ONE LINE in a method and I sat there going from module to module for 20 minutes until I gave up. This program has been getting patches and Frankensteined for years, and many of the original engineers either retired or no longer work with the company. I do have two engineers that worked on it briefly and they’re a great resource, but I was wondering if I can some advice from CS people. Is there a methodical way to untangle spaghetti code? My goal for now is to familiarize myself with it and be comfortable going through and maybe very very carefully make some changes/additions/optimizations. Any tips would be greatly appreciated!
Read the code Try to track whatever coherency might exist with "find usage of" features of an IDE. Drawing charts may help to get an idea of the callgraph. Being completely lost is natural and encouraged -- one of the best ways to learn IMO And then read it again If there aren't any tests, start adding them, so that when you refactor, you're certain you don't play whackamole with things breaking. Once you've read it enough, try to understand what commonalities may exist, see if you can write down a plan for a refactor, and start slicing up that work into manageable chunks.
60
AskComputerScience
ucvk1m
Hello everyone! I’m an EE working with all EE’s. I’ve inherited a major monstrosity of a program (Python). There are methods that call methods in classes that inherit and use attributes from another classes which have methods that call other modules…etc etc. I tried to track down ONE LINE in a method and I sat there going from module to module for 20 minutes until I gave up. This program has been getting patches and Frankensteined for years, and many of the original engineers either retired or no longer work with the company. I do have two engineers that worked on it briefly and they’re a great resource, but I was wondering if I can some advice from CS people. Is there a methodical way to untangle spaghetti code? My goal for now is to familiarize myself with it and be comfortable going through and maybe very very carefully make some changes/additions/optimizations. Any tips would be greatly appreciated!
First "methods calling methods calling methods" is actually encouraged. The alternatives are monoliths of code that are even harder to understand and maintain. It's always challenging to work yourself into an unknown code base, learning what is where and how everything is connected. This is always going to need time. What you can look out for is whether the method and variable names are sensible and expressive. "Can you 'read' the code and understand the gist of it or do you need to parse everything?" A somewhat simple example would be: #region get private phone and mobile numbers var eaddrs = new List(); foreach (var eaddr in eaddrtbl) { if ((eaddr.Type == "Mobile" || eaddr.Type == "Phone") && eaddr.IsPrivate) { eaddrs.add(eaddr); } } #endregion On it's own it's not terribly hard to understand but it does take up 10 lines and burdens your mind with three constructs (define-assign-separation, loop and branch). If your method does 20 such things with some additional nesting that gets hard to follow. Something like Linq can help shorten it: var eaddrs = eaddrtbl.Where(eaddr => (eaddr.Type == "Mobile" || eaddr.Type == "Phone") && eaddr.IsPrivate ).ToList(); You replaced 3 constructs and 10 lines with 1 construct and 3 lines. But a bunch of those still add up. How about: var electronicAddresses = electronicAddressTable.getPrivatePhoneOrMobiles(); You can easily have 20 such lines in a method and it's still very easy to understand. There are very few instances where such a replacement is overkill IF, and only if, your naming is expressive of what it does. Sure comments could add this information but they are inert documentation and documentation costs effort to create and maintain. // get private phone and mobile numbers var lstAdEl = tAdEl.getPrPh(); Little purely structural changes like that can help immensely when getting a grip on a less than ideal codebase. Martin Fowler's [website](https://refactoring.com/) and [book](http://martinfowler.com/books/refactoring.html) are something of the canonical work in this regard. Worth reading through although the above is likely going to provide you with so much low hanging fruit to pick that you'll be covered for a good while. Also, like others said I would look into automated testing, particularly Unit Testing and start putting it into place before you start more advanced refactorings. Unit Testing allows you to define things you expect to be true from a piece of code and quickly check whether they are still true after your changes (be it from refactoring or "productive" modifications) Finally be aware that there is a difference between ugly code and code you just don't understand yet. But they feel very much alike when you first meet them. Obviously you gonna want to have source control in place where you can check in freely so that you can rewind when you fuck up. It should go without saying these days but just in case...
40
AskComputerScience
ucvk1m
Hello everyone! I’m an EE working with all EE’s. I’ve inherited a major monstrosity of a program (Python). There are methods that call methods in classes that inherit and use attributes from another classes which have methods that call other modules…etc etc. I tried to track down ONE LINE in a method and I sat there going from module to module for 20 minutes until I gave up. This program has been getting patches and Frankensteined for years, and many of the original engineers either retired or no longer work with the company. I do have two engineers that worked on it briefly and they’re a great resource, but I was wondering if I can some advice from CS people. Is there a methodical way to untangle spaghetti code? My goal for now is to familiarize myself with it and be comfortable going through and maybe very very carefully make some changes/additions/optimizations. Any tips would be greatly appreciated!
Try to split the code in "function calling function". For each function, describe what the function do (or what you think it does, you can change it latter). Read the code and write what you understand of the function and then go deeper. Using a debugger (pdb) could help a lot. It's not necesary to "go deeper" if you can summary what a function does in few words (somethimes are just edge cases for a X process, just write "edge case for X"). The first time is always the hardest because everything is new, but after some time doing it the function will call functions you already described. You should try to start with not so complex functions.
30
AskComputerScience
ud5btb
This came up in response to Elon Musks acquisition of Twitter. Full quote: > In principle, I don’t believe anyone should own or run Twitter. It wants to be a public good at a protocol level, not a company. Solving for the problem of it being a company however, Elon is the singular solution I trust. I trust his mission to extend the light of consciousness. Source: https://twitter.com/jack/status/1518772756069773313 All I can imagine is that he believes that there should be an open protocol (like there are protocols for email, presence, etc.) that allowed different implementation of Twitter-like technology to communicate "tweets" and users that is outside the ownership of any single company.
Kind’ve a random word choice but he means he wants what makes Twitter a public good to be built into the platform itself. As he points out, there are two distinct components to a huge company like twitter. There is the company/shareholder/internal political side and then there is the technology that exists underneath the platform as a whole.
150
AskComputerScience
ud5btb
This came up in response to Elon Musks acquisition of Twitter. Full quote: > In principle, I don’t believe anyone should own or run Twitter. It wants to be a public good at a protocol level, not a company. Solving for the problem of it being a company however, Elon is the singular solution I trust. I trust his mission to extend the light of consciousness. Source: https://twitter.com/jack/status/1518772756069773313 All I can imagine is that he believes that there should be an open protocol (like there are protocols for email, presence, etc.) that allowed different implementation of Twitter-like technology to communicate "tweets" and users that is outside the ownership of any single company.
I think he means Twitter should be something more like SMTP (the "Email" protocol) or HTTP (the "Web" protocol) - an open protocol that anyone can implement competing clients and/or servers for, rather than a single app/service provided by a single company.
70
AskComputerScience
ud5btb
This came up in response to Elon Musks acquisition of Twitter. Full quote: > In principle, I don’t believe anyone should own or run Twitter. It wants to be a public good at a protocol level, not a company. Solving for the problem of it being a company however, Elon is the singular solution I trust. I trust his mission to extend the light of consciousness. Source: https://twitter.com/jack/status/1518772756069773313 All I can imagine is that he believes that there should be an open protocol (like there are protocols for email, presence, etc.) that allowed different implementation of Twitter-like technology to communicate "tweets" and users that is outside the ownership of any single company.
Stratechery wrote a piece last week about how Twitter the product can be thought of as distinct from Twitter the broadcast-service/social-graph. https://stratechery.com/2022/back-to-the-future-of-twitter/ While I don't think Dorsey is arguing for the same outcome, I think they are working with similar concepts. When Dorsey talks about the protocol level, I think he is using an analogy to describe the broadcast and social graph services. Or, in other words, all the infrastructure that aggregates, routes, and distributes messages, but not the actual end-user applications themselves.
50
AskComputerScience
udhs9e
What's the best IDE for Rust?
I think the most common editor/plugin combinations are (in no particular order): 1. VS Code + Rust Analyzer extension 2. JetBrains CLion or Intellij + Rust Plugin 3. neovim + lsp + Rust Analyzer 4. vim + coc + Rust Analyzer Basically any editor that supports LSP protocol with Rust Analyzer will work.
500
LearnRust
udhs9e
What's the best IDE for Rust?
Intellij comes with many features but it has a yearly fee (in my opinion worth it). VSCode is free and you can equip it with rust-analyzer (and other plugins of your choice) and you’ll be set Edit: Intellij has the community (free) version too! My bad I forgot about the fact you could get the rust plugin in that one too
110
LearnRust
udhs9e
What's the best IDE for Rust?
Emacs + lsp + rust analyzer is awesome; IntelliJ + Rust plug-in is great—recently published Zero to Production in Rust makes an argument for why IntelliJ is the best option as of publication. I’m sure more people are using VSCode than any of the other options put together though.
70
LearnRust
udvlex
Hi, thanks for taking the time. I'm looking for the the rightful owner of a YouTube video. Tried reverse video/image research with no success. any ideas would be very much appreciated
This is one of the great mysteries of computer science, and there are entire divisions of researchers at MIT working on exactly this problem. It may take some breakthrough in quantum computing before this type of high level analysis is possible. What an incredibly relevant question to computer science as a field.
90
AskComputerScience
udvlex
Hi, thanks for taking the time. I'm looking for the the rightful owner of a YouTube video. Tried reverse video/image research with no success. any ideas would be very much appreciated
That's a legal question.
70
AskComputerScience
ue6aoe
So my lecture slides says: >Time between the moment a very short message leaves a machine A until it arrives at machine B (i.e., between A sending and B receiving) My question is, is this measurement for 1 bit? If not, say machine A sends a group of bits. Then, does the measurement start when the first bit leaves A or when the last bit leaves A?
I think they're saying "a very short message" to imply that the time between the first and last bit leaving A is negligible, in comparison to the latency of the system.
40
AskComputerScience
ue6aoe
So my lecture slides says: >Time between the moment a very short message leaves a machine A until it arrives at machine B (i.e., between A sending and B receiving) My question is, is this measurement for 1 bit? If not, say machine A sends a group of bits. Then, does the measurement start when the first bit leaves A or when the last bit leaves A?
You know, I'm not sure if I've seen a definite answer to that. We can philosophize, though: can a message be considered "sent" if not all of it has been sent, or considered "received" if not all of it has been received?
30
AskComputerScience
uefjom
Background: I am an undergrad student and have been using Java for the past 5 years. In march I started applying for internships labelled "Java" "Spring MVC" "JDBC" "J2EE" etc. I got an offer from a 6 year old company with 30 employees listed in their IT department on linkedin. Now when I asked them yesterday to give me a heads up on what I'll be working with/on they tell me it would be MERN stack, C#, python and php The internship will start in 9 days and I received that email yesterday. Please advise me how to learn all this to a level that I can at least understand what's going on if presented some code. Mind you I have never touched JS and only yesterday I realised you can make functions inside functions in it. I need serious guidance on how to handle this because I can't leave this opportunity since I don't have any other offers currently and I am still applying to as many as I can find
MERN is MongoDB, Express, React, Node. On top of that they've thrown THREE more whole programming languages. No way you're going to learn even the basics of all of that in 9 days. But you've already learned one programming language, you'll be fine with the others. Yes it will take time. But more time than you have right now to get any significant head way, so - in good Dr. House fashion (no point in testing for a disease when the patient will be dead before you get the results) - ignore those. Maybe if you've got time get a feel for the syntax. You could put some time into learning the basics of node and express. But there are no big gotchas here and a huge amount to learn. This is like trying to learn all the java framework in a week. Frameworks and APIs are always stuff that you're going to learn as you use them so don't stress it. This leaves Mongo DB and React and these are the things I'd start with. Not only are they the only techs mentioned of their kind, they are also fundamentally different enough from what you've likely used before that they are going to be your biggest stumbling blocks. But in the end: they accepted you for this internship knowing your qualifications. You'll be expected to learn this stuff *during* - not before - your internship.
60
AskComputerScience
uehlqi
currently i have something like this: Enum1 { Val1(Enum2), Val2, more values... } Enum2 { Val1(String), Val2, more values... } let event = Enum1::Val1(Enum2::Val1(String::from("yay"))); match event { Enum1::Val1(Enum2::Val1(string_value)) { if string_value == "yay" then { println!("got yay, yay"); } } more patterns ... } Is there better way to match the string_value here?
You could look at `if let`
30
LearnRust

No dataset card yet

New: Create and edit this dataset card directly on the website!

Contribute a Dataset Card
Downloads last month
2
Add dataset card