1564915178
Originally published by Michael Snoyman at dzone.com
This post is part of a series, Rust Crash Course. You can read all the posts:
In this blog post, I want to explain:
I'm getting to work on this series due to increased Rust usage at FP Complete.
I'm a strong believer in using the compiler to help eliminate bugs. No programming language can eliminate all bugs and even the best-designed language will typically need to leave developers plenty of wiggle room to shoot themselves in the foot. Still, there's significant value in safety and long-term maintainability of projects that use languages with this focus.
For about ten years now, my primary language has been (and continues to be) Haskell. It gets a lot of things right here, such as immutability, explicit effects, and strong typing. But I've got two problems with an intense focus on Haskell:
Like many others, I've been hearing a buzz around Rust for years. Two or so years ago, I started playing around with it more, and have been steadily dedicating more personal time to it. But recently, we've had more Rust interest at work, and therefore we've been expanding our internal Rust team.
We're a globally distributed team at FP Complete, and we make a heavy push towards using written communication tools wherever possible. This also overlaps heavily with training material. As I do more training (both internally, and for customers), I'm discovering places where:
This series is intended to collect both initial pointers of how to get started with Rust and hard-learned lessons of how to avoid getting stuck. Some of these stumbling blocks may favor the kind of audience I'm working with directly (lots of Haskell and DevOps engineers), but that will likely change over time.
I'm gearing this series towards the Rust curious. I'm assuming programming knowledge, and some basic idea of what Rust is about, but no real knowledge of the language itself. I'll try to call out when you should go read the Rust book.
If you're a Java user, a Rubyist, or a Haskeller, and Rust intrigues you, I hope this will help you. And maybe even Rustaceans will enjoy seeing the pain points I find myself and others are hitting.
There is already really good material on Rust available from rust-lang.org. I have no intention of trying to replace that. Instead, I'll assume that people are reading through the Rust book, and point to sections where appropriate.
One concrete example: I don't intend to spend a lot of time talking about Rust syntax, or explaining that it's an expression-oriented language. The book covers that.
Instead, I want to give people:
And on that note...
A few people on Twitter asked me to share some Rust gotchas, especially coming from the perspective of a Haskell developer. I'll certainly be covering more gotchas going forward, but I wanted to give some examples in this first post so you can get a feel for the kinds of things we'll be addressing in the series. I'm not going to be explaining details of these problems here; that's what the series is for!
Just so you know: there's no content following these examples, besides the Disqus comments below. If you're not interested in the gotchas, feel free to quit reading now and stay tuned for more posts.
I've got a simple mental model in Haskell. Values are all immutable, period. A few special reference types allow me to mutate their contents. And mutating like that is an effect tracked in the type system.
From that perspective, Rust is a bit surprising. Here's one:
fn main() { let i: isize = 1; let j: isize = foo(i); println!("{}", j); } fn foo(mut i: isize) -> isize { i += 1; i }
Wait a second... i
is immutable. Then I pass it to foo
, and it becomes mutable. Then I return this mutable value as an immutable value. What?
I assure you, this ultimately makes sense, but it's kind of surprising. Also, the fact that x: &mut isize
and mut x: &mut isize
are both real things that mean different things:
fn main() { let mut i: isize = 1; let mut j: isize = 2; foo(&mut i, &mut j); println!("{} {}", i, j); } fn foo<'a>(mut i: &'a mut isize, j: &'a mut isize) { *i *= 10; i = j; *i *= 10; }
I was warned about this one and blew it off. I thought to myself, 'there's no way a Haskeller, trained in the arts of String
, strict Text
, lazy Text
, ByteString
s and more could be daunted.' I was wrong.
fn main() { let hello1 = String::from("Hello, "); let hello2 = String::from(", hello!"); let name = "Alice"; println!("{}", hello1 + name); println!("{}", name + hello2); }
Nope, the code above doesn't compile.
There are a number of "magic" things that happen in Rust in the name of ergonomics. Often, they work perfectly and save a lot of frustration. And sometimes, they fail. Look at this broken code:
fn main() { for arg in std::env::args().skip(1) { respond(arg); } } fn respond(arg: &str) { match arg { "hi" => println!("Hello there!"), "bye" => println!("OK, goodbye!"), _ => println!("Sorry, I don't know what {} means", arg), } }
You'll get an error message:
expected &str, found struct `std::string::String`
Oh, well that makes sense! I need to get a reference to a str
instead of the String
I got from args()
. Easy enough to fix:
respond(&arg);
But then I realize that the respond
function is silly and inline the match
:
fn main() { for arg in std::env::args().skip(1) { match &arg { "hi" => println!("Hello there!"), "bye" => println!("OK, goodbye!"), _ => println!("Sorry, I don't know what {} means", arg), } } }
I remembered to match on &arg
instead of arg
, so you'd think it would be fine. But it isn't:
| ^^^^ expected struct `std::string::String`, found str | = note: expected type `&std::string::String` found type `&'static str`
Huh, that's weird. In order to figure out what's going on here, you have to understand quite a few details of the deref magic going on behind the scenes. I dare say some of this magic is even a leaky abstraction (don't worry, it's still zero cost). You can solve this with either:
match &*arg {
or
match arg.as_ref() {
The biggest pain points I've encountered so far in my Rust odyssey are all around moving data into closures. I've been spoiled by Haskell: I like to use closures constantly, and am used to garbage collection just letting it all magically work.
I've got some real head-scratchers to demonstrate later, but have fun with this relatively simple example:
fn main() { let hello = String::from("Hello, "); let greet = |name| hello + name; println!("{}", greet("Alice")); println!("{}", greet("Bob")); }
Originally published by Michael Snoyman at dzone.com
========================================
Thanks for reading :heart: If you liked this post, share it with all of your programming buddies! Follow me on Facebook | Twitter
☞ The Rust Programming Language
☞ Rust: Building Reusable Code with Rust from Scratch
☞ Programming in Rust: the good, the bad, the ugly.
☞ An introduction to Web Development with Rust for Node.js Developers
#rust #web-development
1643176207
Serde
*Serde is a framework for serializing and deserializing Rust data structures efficiently and generically.*
You may be looking for:
#[derive(Serialize, Deserialize)]
Click to show Cargo.toml. Run this code in the playground.
[dependencies]
# The core APIs, including the Serialize and Deserialize traits. Always
# required when using Serde. The "derive" feature is only required when
# using #[derive(Serialize, Deserialize)] to make Serde work with structs
# and enums defined in your crate.
serde = { version = "1.0", features = ["derive"] }
# Each data format lives in its own crate; the sample code below uses JSON
# but you may be using a different one.
serde_json = "1.0"
use serde::{Serialize, Deserialize};
#[derive(Serialize, Deserialize, Debug)]
struct Point {
x: i32,
y: i32,
}
fn main() {
let point = Point { x: 1, y: 2 };
// Convert the Point to a JSON string.
let serialized = serde_json::to_string(&point).unwrap();
// Prints serialized = {"x":1,"y":2}
println!("serialized = {}", serialized);
// Convert the JSON string back to a Point.
let deserialized: Point = serde_json::from_str(&serialized).unwrap();
// Prints deserialized = Point { x: 1, y: 2 }
println!("deserialized = {:?}", deserialized);
}
Serde is one of the most widely used Rust libraries so any place that Rustaceans congregate will be able to help you out. For chat, consider trying the #rust-questions or #rust-beginners channels of the unofficial community Discord (invite: https://discord.gg/rust-lang-community), the #rust-usage or #beginners channels of the official Rust Project Discord (invite: https://discord.gg/rust-lang), or the #general stream in Zulip. For asynchronous, consider the [rust] tag on StackOverflow, the /r/rust subreddit which has a pinned weekly easy questions post, or the Rust Discourse forum. It's acceptable to file a support issue in this repo but they tend not to get as many eyes as any of the above and may get closed without a response after some time.
Download Details:
Author: serde-rs
Source Code: https://github.com/serde-rs/serde
License: View license
1624395600
Learn the most popular NoSQL / document database: MongoDB. In this quickstart tutorial, you’ll be up and running with MongoDB and Python.
⭐️Course Contents⭐️
⌨️ (0:00:00) Welcome
⌨️ (0:04:33) Intro to MongoDB
⌨️ (0:07:49) How do document DBs work?
⌨️ (0:10:34) Who uses MongoDB
⌨️ (0:13:02) Data modeling
⌨️ (0:16:30) Modeling guidelines
⌨️ (0:22:11) Integration database
⌨️ (0:24:23) Getting demo code
⌨️ (0:30:07) How ODMs work?
⌨️ (0:32:55) Introduction to mongoengine
⌨️ (0:34:01) Demo: Registering connections with MongoEngine
⌨️ (0:37:20) Concept: Registering connections
⌨️ (0:39:14) Demo: Defining mongoengine entities (classes)
⌨️ (0:45:22) Concept: mongoengine entities
⌨️ (0:49:03) Demo: Create a new account
⌨️ (0:56:55) Demo: Robo 3T for viewing and managing data
⌨️ (0:58:18) Demo: Login
⌨️ (1:00:07) Demo: Register a cage
⌨️ (1:10:28) Demo: Add a bookable time as a host
⌨️ (1:16:13) Demo: Managing your snakes as a guest
⌨️ (1:19:18) Demo: Book a cage as a guest
⌨️ (1:33:41) Demo: View your bookings as guest
⌨️ (1:41:29) Demo: View bookings as host
⌨️ (1:46:18) Concept: Inserting documents
⌨️ (1:47:28) Concept: Queries
⌨️ (1:48:09) Concept: Querying subdocuments with mongoengine
⌨️ (1:49:37) Concept: Query using operators
⌨️ (1:50:24) Concept: Updating via whole documents
⌨️ (1:51:46) Concept: Updating via in-place operators
⌨️ (1:54:01) Conclusion
📺 The video in this post was made by freeCodeCamp.org
The origin of the article: https://www.youtube.com/watch?v=E-1xI85Zog8&list=PLWKjhJtqVAbnqBxcdjVGgT3uVR10bzTEB&index=10
🔥 If you’re a beginner. I believe the article below will be useful to you ☞ What You Should Know Before Investing in Cryptocurrency - For Beginner
⭐ ⭐ ⭐The project is of interest to the community. Join to Get free ‘GEEK coin’ (GEEKCASH coin)!
☞ **-----CLICK HERE-----**⭐ ⭐ ⭐
Thanks for visiting and watching! Please don’t forget to leave a like, comment and share!
#mongodb #python #python crash course #mongodb with python crash course - tutorial for beginners #beginners #mongodb with python crash course
1629837300
What we learn in this chapter:
- Rust number types and their default
- First exposure to #Rust modules and the std::io module to read input from the terminal
- Rust Variable Shadowing
- Rust Loop keyword
- Rust if/else
- First exposure to #Rust match keyword
=== Content:
00:00 - Intro & Setup
02:11 - The Plan
03:04 - Variable Secret
04:03 - Number Types
05:45 - Mutability recap
06:22 - Ask the user
07:45 - First intro to module std::io
08:29 - Rust naming conventions
09:22 - Read user input io:stdin().read_line(&mut guess)
12:46 - Break & Understand
14:20 - Parse string to number
17:10 - Variable Shadowing
18:46 - If / Else - You Win, You Loose
19:28 - Loop
20:38 - Match
23:19 - Random with rand
26:35 - Run it all
27:09 - Conclusion and next episode
1591267050
Welcome to Flask Crash Course For Beginners [Python Web Development], in this video we are going to talk about about different concepts in flask. so as you k…
#python #flask crash course #flask #crash course #progaming
1593242571
Techtutorials tell you the best online IT courses/training, tutorials, certification courses, and syllabus from beginners to advanced level on the latest technologies recommended by Programming Community through video-based, book, free, paid, Real-time Experience, etc.
#techtutorials #online it courses #mobile app development courses #web development courses #online courses for beginners #advanced online courses