Rust Programming

8049 readers
3 users here now

founded 5 years ago
MODERATORS
1
 
 

(I'm just starting off with rust, so please be patient)

Is there an idiomatic way of writing the following as a one-liner, somehow informing rustc that it should keep the PathBuf around?

// nevermind the fully-qualified names
// they are there to clarify the code
// (that's what I hope at least)

let dir: std::path::PathBuf = std::env::current_dir().unwrap();
let dir: &std::path::Path   = dir.as_path();

// this won't do:
// let dir = std::env::current_dir().unwrap().as_path();

I do understand why rust complains that "temporary value dropped while borrowed" (I mean, the message says it all), but, since I don't really need the PathBuf for anything else, I was wondering if there's an idiomatic to tell rust that it should extend its life until the end of the code block.

2
 
 

Rust ownership is a fundamental part of the language.

I’ve summarized the basic concepts here as a learning exercise for myself.

I’m sharing this to gather feedback, corrections, and suggestions.

Feel free to offer improvements wherever needed!

3
 
 

We also have documentation to setup the dev environment: https://join-lemmy.org/docs/contributors/02-local-development.html

If you have questions, feel free to ask here, in the relevant issue or in matrix.

4
 
 

Which of these code styles do you find preferable?

First option using mut with constructor in the beginning:

  let mut post_form = PostInsertForm::new(
    data.name.trim().to_string(),
    local_user_view.person.id,
    data.community_id,
  );
  post_form.url = url.map(Into::into);
  post_form.body = body;
  post_form.alt_text = data.alt_text.clone();
  post_form.nsfw = data.nsfw;
  post_form.language_id = language_id;

Second option without mut and constructor at the end:

  let post_form = PostInsertForm {
    url: url.map(Into::into),
    body,
    alt_text: data.alt_text.clone(),
    nsfw: data.nsfw,
    language_id,
    ..PostInsertForm::new(
      data.name.trim().to_string(),
      local_user_view.person.id,
      data.community_id,
    )
  };

You can see the full PR here: https://github.com/LemmyNet/lemmy/pull/5037/files

5
 
 
6
 
 

Rust Project goals for 2024

https://blog.rust-lang.org/2024/08/12/Project-goals.html

cc: @rust@lemmy.ml

7
 
 

#rust folks it's supposed to throw this error without lazy_static crate , but it doesn't?
https://git.sr.ht/~carnotweat/morning-rust/tree/main/item/sum.rs#L14
cc @rust @learningrustandlemmy

8
 
 

cross-posted from: https://lemmy.world/post/18129059

This feels like it should already be a feature in a terminal. But I didn't find anything that let me do this efficiently.

I had a rust library for converting list like 1-4,8-10 into vectors, but thought I'd expand it into a command line command as well, as it is really useful when I want to run batch commands in parallel using templates.

I wanted to share it since it might be a useful simple command for many people.

9
 
 

Hi all,

mpv communities seem to be tiny in lemmy, so I'm sharing it here.

This is a program I made for music control from local network.

You can run it in a computer with some local media files, or youtube links or any other links yt-dlp supports. And then with the server, you can control the media player and the playlist from any devices in your local network. So that you can just show a QR code or something to house guests for parties, or have it bookmarked within family to control the music.

I wanted to make something similar to how youtube app let's you play in TV and such, but my skills were not enough to do that. So I tried a simple alternative that works with computers. In an ideal world, I could make "Play with local mpv server" option come while on other android apps, but I have zero experience in android app development and it looks complicated.

I know some other programs also give option to control media, but I wanted to give it a go with a simple implementation. Making the web-server was a tricky part. Only tutorial from the rust book was useful here as every other web server developement in rust seems to be async ones using libraries so I would have to make a complicated system to communicate with the mpv. Using the simple Tcp connection let me make a thread with mpv instance in the scope. I do need to support https and file uploads and other things, but I haven't had any luck finding a solution that works with simple Tcp connection like in the tutorial. Let me know if you know anything.

Github: https://github.com/Atreyagaurav/local-mpv

10
 
 

For context, I am using the libraries bevy and print_typewriter.

I noticed that before the program even starts, I am able to type in characters. This is bad, since when I ask for the user's input, the previous characters are included inside of it.

How do I make sure that only the user's input after the program starts, and after I print a question gets in?

11
12
 
 

This would entail:

  • Pulling in the ClearUrls rules as a git submodule.
  • Reading / transforming the json there into Rust structs.
  • Creating a Rust crate that runs a .clean(input_url) -> String

Lemmy issue: https://github.com/LemmyNet/lemmy/issues/4905

13
11
submitted 2 months ago* (last edited 2 months ago) by runiq@feddit.org to c/rust@lemmy.ml
 
 
  • Added type diesel_async::pooled_connection::mobc::PooledConnection
  • MySQL/MariaDB now use CLIENT_FOUND_ROWS capability to allow consistent behaviour with PostgreSQL regarding return value of UPDATe commands.
  • The minimal supported rust version is now 1.78.0
  • Add a SyncConnectionWrapper type that turns a sync connection into an async one. This enables SQLite support for diesel-async
  • Add support for diesel::connection::Instrumentation to support logging and other instrumentation for any of the provided connection impls.
  • Bump minimal supported mysql_async version to 0.34

A special thanks goes to @momobel and Wattsense for contributing the SyncConnectionWrapper implementation.

To support future development efforts, please consider sponsoring me on GitHub.

Full Changelog: v0.4.0...v0.5.0

14
15
 
 

It's less than two weeks until our next Rust and NixOS meetup in Mannheim, Germany. We're meeting on the 16th of July at the Mafinex technology center close to the main station. If you want to join us, please sign up for the event on Mobilizon (no account required) or Meetup.com.

https://rheinneckar.events/events/9d740b89-7713-4e19-a112-45aff1670f0f

https://www.meetup.com/hackschool-rhein-neckar/events/301504325/

As first talk, we will hear Andre Dossinger on "Using NixOS for Pragmatical Self-hosting", where he will show us how NixOS can be used in a problem oriented manner to preserve privacy and make complex setups manageable. Questions and discussions are highly encouraged!

Then, we will hear Benjamin Sparks on "Reading from Streams and Writing to Sinks" using Rust and Tokio, with a focus on low runtime overhead, safe buffer management, and robust error handling. He will show us the types and traits Tokio leverages to efficiently decode bytes and encode structured data in a type-safe manner is presented, and give us a practical demonstration of codecs for two different protocols.

Finally, Stefan Machmeier of the EMCL at Heidelberg University will give us an introduction to Nix Flakes, the experimental dependency management system built into Nix since version 2.4 that can be used for reusable Nix libraries as well as your own Nix packages and NixOS configurations.

The talks will be recorded and uploaded after the meetup.

16
 
 

cross-posted from: https://programming.dev/post/16349359

July 2, 2024

Sylvain Kerkour writes:

Rust adoption is stagnating not because it's missing some feature pushed by programming language theory enthusiasts, but because of a lack of focus on solving the practical problems that developers are facing every day.

... no company outside of AWS is making SDKs for Rust ... it has no official HTTP library.

As a result of Rust's lack of official packages, even its core infrastructure components need to import hundreds of third-party crates.

  • cargo imports over 400 crates.

  • crates.io has over 500 transitive dependencies.

...the offical libsignal (from the Signal messaging app) uses 500 third-party packages.

... what is really inside these packages. It has been found last month that among the 999 most popular packages on crates.io, the content of around 20% of these doesn't even match the content of their Git repository.

...how I would do it (there may be better ways):

A stdx (for std eXtended) under the rust-lang organization containing the most-needed packages. ... to make it secure: all packages in stdx can only import packages from std or stdx. No third-party imports. No supply-chain risks.

[stdx packages to include, among others]:

gzip, hex, http, json, net, rand

Read Rust has a HUGE supply chain security problem


Submitter's note:

I find the author's writing style immature, sensationalist, and tiresome, but they raise a number of what appear to be solid points, some of which are highlighted above.

17
 
 

The June edition of "This Month in Rust GameDev" has just landed!. With it, we have also added the option to subscribe to the newsletter by email. You can find the subscription form by scrolling down on https://gamedev.rs/.

This is also your call for submissions! Got a game you're tinkering on? A crate for fellow game devs? Do you want to share a tutorial you've made? Are you excited about a new feature in your favorite engine? Share it with us!

You can add your news to this month's WIP newsletter and mention the current tracking issue in your PR to get them included. We will then send out the newsletter at the start of next month.

Happy coding 🌟

18
19
submitted 3 months ago* (last edited 3 months ago) by QaspR@lemmy.world to c/rust@lemmy.ml
 
 

Have been struggling to find some nice Rust wallpapers, so I decided to make one for myself.

On the left is Ferris on a canvas. On the right is Corro the unsafe Rusturchin. (The contrast between safe (art-like) and unsafe Rust is supposed to be the joke here.)

Edit: The original image is 1080p. I got the drawings of Ferris and Corro from rustacean.net

19
 
 

cross-posted from: https://lemmy.ml/post/17090149

Hi! I've created a CLI tool for downloading Rust web books (like The Rust Programming Language) as EPUB, so that you can easily read them on your e-book reader. The tool is heavily based on this gist and a lot of proompting.

Check it out here: https://github.com/mawkler/rust-book-to-epub

20
 
 

cross-posted from: https://programming.dev/post/15696807

That was a hard long adventure, massive refactoring with bug-fixing 🥵

21
43
submitted 3 months ago by tmpod to c/rust@lemmy.ml
22
23
 
 

So, apparently the chrome/geckodriver processes will terminate on their own if the user sends ctrl+c to the console. It will not terminate on its own if the program finishes running naturally.

If you're interested in terminating it on your own, like I also was, here is how I went about it.

use std::process::{Child, Command};

fn main() {
	let mut s = Server::default();
	s.start();
	s.shutdown();
}

struct Server {
	child: Option<Child>
}

impl Default for Server {
	fn default() -> Self {
		Self {
			child: None
		}
	}
}

impl Server {
	fn start(&mut self) {
		self.child = Some(Command::new("./chromedriver")
			.spawn()
			.expect("ls command failed to start"));
	}

	fn shutdown(&mut self) {
		input(None); // wait for input so you can observe the process
		self.child.as_mut().unwrap().kill();
		self.child.as_mut().unwrap().wait();
		println!("shutdown");
	}
}

pub fn input(prompt: Option<String>) {
	let mut input = String::new();
	match prompt {
		Some(prompt) => println!("{}", prompt),
		None => ()
	}
	io::stdin().read_line(&mut input).expect("Failed to read input");
}
24
 
 

The May edition of "This Month in Rust GameDev" has just landed!.

With it, we also released a statistical analysis of the survey we ran last month. Thank you very much to the 52 readers who gave us their feedback on how to improve the newsletter! You rock!

This is also your call for submissions. Got a game you're tinkering on? A crate for fellow game devs? Do you want to share a tutorial you've made? Are you excited about a new feature in your favorite engine? Share it with us! You can add your news to this month's WIP newsletter and mention the current tracking issue in your PR to get them included. We will then send out the newsletter at the start of next month.

Happy coding ✨

25
 
 

I’m wondering if anyone knows knows of something like stylelint written in rust? I’ve done some searching but can’t find it, but I feel like it must exist in some form.

I’m switching over to Biome from eslint due to the massive speed improvements and I want to do the same with stylelint.

view more: next ›