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... | 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 t... | `.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 ... | 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 t... | 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 ... | 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 ... | 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... | 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 adva... | 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 adva... | 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 a... | 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... | 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... | `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 the... | 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 the... | 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... | 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 i... | 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 lan... | 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!("... | 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 wan... | 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... | 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 ... | 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 gr... | 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... | 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... | 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... | 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... | 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:
ge... | 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 struc... | 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:
ge... | 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 ran... | 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:
... | >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(... | 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 trai... | 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"
&#x200B;
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,... | 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 i... | 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 d... | 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://... | 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,... | 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,... | 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(co... | 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=fd7cdde... | 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 r... | 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 glo... | 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 r... | 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 syste... | 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().... | 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 ... | 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 discussi... | 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 discussi... | 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 ... | 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(MyEnu... | 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 ... | 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 l... | 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 ... | 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... | 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 ... | 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 her... | 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 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(|er... | 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, Bo... | 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(|er... | 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 cal... | 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,... | 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... | 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()
... | 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 ... | 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 ... | 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 f... | 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: usiz... | 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: usiz... | 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 har... | 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 w... | 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 har... | 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 http... | 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-li... | 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 ... | 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 ... | 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 ... | 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 mindblowin... | 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 mindblowin... | 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... | 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 readab... | 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 ... | 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 ... | 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 f... | 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, ... | 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... | 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, ... | 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... | 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... | 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 tha... | 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... | 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... | 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 discovere... | 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 discovere... | 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 discovere... | **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-4I6... | 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 go... | 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 tha... | 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 go... | 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. ... | 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 go... | 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 c... | 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 mi... | 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 t... | 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 mi... | 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 mi... | 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 ... | 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 t... | 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 ... | 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 ... | 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 m... | 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 ri... | 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_... | You could look at `if let` | 30 | LearnRust |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.