Example from Rust in Action does not work [closed] - rust

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 months ago.
Improve this question
I am following the textbook Rust in Action and trying to write the example on page 71:
When I try to define an args like:
let args = App::new("chapter1")
.about("Searches for patterns!").arg(Arg::with_name("pattern"))
.help("The pattern to look for!")
.takes_value(true)
.required(true).get_matches();
I get an error,
no method named `takes_value` found for struct `App` in the current scope
items from traits can only be used if the trait is in scoperustcE0599
any_arg.rs(37, 8): the method is available for `App<'_, '_>` here
main.rs(1, 1): the following trait is implemented but not in scope; perhaps add a `use` for it:: `use clap::args::any_arg::AnyArg;
Can anyone tell me what the problem is? Because it seems to work in the textbook?

What if you try instead (sorry, didn't test it):
let args = App::new("chapter1")
.about("Searches for patterns!").arg(Arg::with_name("pattern")
.help("The pattern to look for!")
.takes_value(true))
.required(true).get_matches();
or
let args = App::new("chapter1")
.about("Searches for patterns!").arg(Arg::with_name("pattern")
.help("The pattern to look for!")
.takes_value(true)
.required(true))
.get_matches();
takes_value() in clap (version 3.*) is a method from the struct Arg, not App. The parentheses you show imply that it was referring to the struct App.

Related

How to pass an object as a parameter to another function in Rust? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 11 months ago.
Improve this question
This is my code:
use handlebars::{Handlebars};
use serde_json::json;
use std::error::Error;
use std::fs;
use std::io::{BufReader, Read};
use std::path::Path;
use std::fs::File;
pub const base_path: &str = "/Users/myname/Desktop/projectname/";
fn main() -> Result<(), Box<dyn Error>>{
let mut reg = Handlebars::new();
// problem zone: how to pass the reg object here?
//register_template_files(reg);
Ok(())
}
// using registry object
fn register_template_files(registry: registry) {
//using object of type Registry to register Templates
}
I don't know Rust good enough to know how to pass the reg object to another function. How to do this?
Instead of registry: registry, you need to use registry: Registry and import that type from handlebars.
You probably also want to use references registry: &Registry, because what looks like pass-by-value instead is the notation for move semantics in Rust, which basically means that any value you pass into a function is thereafter no longer valid and trying to do that will provoke errors from the compiler.

Learning rust getting compile error when declaring None

I'm currently reading the official rust-lang book (the one on their website/documentation) and I'm taking notes by copying code and writing comments for everything. I'm currently on chapter 6, Options enum type. Based on the book and some Rustlings code I came across while googling the following should be possible based on the the official book
let none: Option<i32> = None;
I also have the following notes in comment form next to it :
If we use None rather than Some, we need to tell Rust what type of Option<T> we have, because the compiler can’t infer the type that the Some variant will hold by looking only at a None value. And I mean it satisfies the requirement but I keep getting the following error:
mismatched types
expected enum `main::Option<i32>`
found enum `std::option::Option<_>`
I did come across this which works:
let _equivalent_none = None::<i32>;
Can anyone explain why one works but the other doesn't? The official book doesn't even mention the second variant (that doesn't throw an error). Is the newest version different from what's documented in the book?
It appears that you have defined your own enum called Option in your program. Thus, there are two different types called Option: yours (main::Option), and the standard one (std::option::Option). The variable none has type main::Option, but None is of type std::option::Option.
Obvious solution is to just delete your own enum. If, however, for the sake of experiment you do want to create an instance of your own enum called Option, and assign the value of None to it, you'd need to qualify None:
let none: Option<i32> = Option::None;
The problem is that defining an enum Option { None, … } brings a new Option into scope, shadowing the std::option::Option imported by std::prelude by default. However, enum Option { None, … } does not bring a new None into scope, so the std::option::Option::None imported by prelude is still there.
So, you have two options:
Use: let none: Option<i32> = Option::None;, specifying which none to use explicitly.
Add a use crate::Option::*; below your enum, bringing your own None into scope.

Why ES6 (7/8...) is able to be compatible with ES5(3) since there is so much difference in grammar? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 1 year ago.
Improve this question
Addition: Why Python3 choose to design new features at cost of compatibility? Is there anything to do with the nature of language?
Why ES6 (7/8…) is able to be compatible with ES5(3) since there is so much difference in grammar?
There aren't differences so much as additions. When new grammar/syntax is added in JavaScript, it's defined carefully so that it would have been a syntax error in earlier versions. That's important, because maintaining backward compatibility with the mind-bogglingly huge amount of JavaScript code out in the wild is an important goal for the committee that moves JavaScript forward (ECMA's TC39). (Backward compatibility isn't 100%, but it's about 99.9999%.) But if something new would have been a syntax error before, then there isn't any working code out there that has the new thing.
For example: Adding async functions. In JavaScript from the beginning, a function declaration looks like this:
function example() {
// ...
}
To create async functions, it became possible to put async in front of function:
async function example() {
// ...
}
That's new grammar. It only works because before it was added, that would have been a syntax error, the same one you get if you do this today:
blah function example() {]
// ...
}
Similarly, with parameter default values, you specify the default value with an = and an expression in the parameter list:
function example(param = "default") {
// ...
}
That was a syntax error until it was added. So were arrow functions, generator functions, class syntax, nullish coalescing, optional chaining, destructuring, and other new grammar/syntax.
So since these would have been syntax errors, they don't exist in working code out in the wild.

Why is Rust's .expect() called expect? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 1 year ago.
Improve this question
Rust's .expect() is one of the most surprising names in the Result/Option space. While unwrap makes sense -- get a value from a Result by "unwrapping" it -- expect is surprisingly counterintuitive (to me).
Since so much of Rust is inspired by conventions from functional programming languages, I have been assuming that this is another example of "strange homage to obscurity," but when I asked the Duck it couldn't find an answer for me.
So, I give up. Why is .expect() the name for Rust's .unwrap_or_panic_with_this_message() function? Is this a reference to a feature in yet another functional language? Is it back-handed shade (or a complement) to Tcl? The result of too many late nights and too much Espresso at Mozilla?
What is the etymology of this plucky (but fierce!) little member of the standard library?
Edit:
Great news, everyone! After more than a year, we now have both an "explanation" in #GManNickG's tremendously well-researched and documented answer, below, and a "mental model" provided by #Peng's comment and link:
https://doc.rust-lang.org/std/error/index.html#common-message-styles
In short, it is now recommended that diagnostics for expect() should be written as "expect...should" or maybe "expect...should have". This makes more sense in the diagnostic output (see the link for examples) but also makes the source code scan better:
foo.expect("something bad happened") // NO!
foo.expect("gollywumpus should be current") // YES!
Summary:
No explicit reason for the name is given. However, it is incredibly likely the name comes from the world of parsers, where one "expects" to see a particular token (else the compilation fails).
Within rustc, the use of expect-like functions long predate use within Option. These are functions like expect(p, token::SEMI) to expect to parse a semicolon and expect_word(p, "let") to expect to parse the let keyword. If the expectation isn't met, compilation fails with an error message.
Eventually a utility function was added within the compiler that would expect not a specific token or string, but that a given Option contained a value (else, fail compilation with the given error message). Over time this was moved to the Option struct itself, where it remains today.
Personally, I don't find it unusual at all. It's just another verb you can do to the object, like unwrapping or taking or mapping its value. Expecting a value (else, fail) from your Option seems quite natural.
History:
The oldest commit of note is the following:
https://github.com/rust-lang/rust/commit/b06dc884e57644a0c7e9c5391af9e0392e5f49ac
Which adds this function within the compiler:
fn expect<T: copy>(sess: session, opt: option<T>, msg: fn() -> str) -> T {
alt opt {
some(t) { t }
none { sess.bug(msg()); }
}
}
As far as I can tell, this is the first function named "expect" that deals with inspecting an Option. Observe in particular this example use-case within the commit (which was implementing support for class methods!):
#debug("looking up %? : %?", def, class_doc);
let the_field = expect(tcx.sess,
decoder::maybe_find_item(def.node, class_doc),
{|| #fmt("get_field_type: in class %?, field ID %? not found",
class_id, def)});
If the result of decoder::maybe_find_item is None, compilation will fail with the given error.
I encourage you to look at the parser code in this commit - there is extensive use of other expect-esque functions: e.g., expect(p, token::RPAREN) and expect_word(p, "let"). The name of this new function is almost obvious in this environment.
Eventually, the utility of this function was extracted and placed within Option itself:
https://github.com/rust-lang/rust/commit/e000d1db0ab047b8d2949de4ab221718905ce3b1
Which looked like:
pure fn expect<T: copy>(opt: option<T>, reason: str) -> T {
#[doc = "
Gets the value out of an option, printing a specified message on failure
# Failure
Fails if the value equals `none`
"];
alt opt { some(x) { x } none { fail reason; } }
}
It's worth noting that sometime later, there was eventually an (additional) function named unwrap_expect added in:
https://github.com/rust-lang/rust/commit/be3a71a1aa36173ce2cd521f811d8010029aa46f
pure fn unwrap_expect<T>(-opt: option<T>, reason: ~str) -> T {
//! As unwrap, but with a specified failure message.
if opt.is_none() { fail reason; }
unwrap(opt)
}
Over time these were both subsumed by an Expect trait, which Option implemented:
https://github.com/rust-lang/rust/commit/0d8f5fa618da00653897be2050980c800389be82
/// Extension trait for the `Option` type to add an `expect` method
// FIXME(#14008) should this trait even exist?
pub trait Expect<T> {
/// Unwraps an option, yielding the content of a `Some`
///
/// # Failure
///
/// Fails if the value is a `None` with a custom failure message provided by
/// `msg`.
fn expect<M: Any + Send>(self, m: M) -> T;
}
Spoiler for that TODO: that trait no longer exists. It was removed shortly after per:
https://github.com/rust-lang/rust/issues/14008.
More or less this is where we are at today.
I think the most likely conclusion is that the use of expect as a meaningful function name long predates its use in Option. Given it says what it does (expect a value or fail) there is little reason to break the pattern.

Build Option<Vec<String>> from Iterator<Item = String> [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I have the following logic implemented:
let assigned_courses: Option<Vec<String>> =
schools.courses.iter().map(|c| c.to_string()).collect();
Since this is an optional variable, I get the error:
value of type `std::option::Option<Vec<std::string::String>>` cannot
be built from `std::iter::Iterator<Item=std::string::String>`
How do I handle this issue? If it is not optional, it does not throw this error.
Why not?
let assigned_courses: Vec<String> =
schools.courses.iter().map(ToString::to_string).collect();
Or if you really need an Option for later usage within your context
let assigned_courses: Option<Vec<String>> =
Some(schools.courses.iter().map(ToString::to_string).collect());

Resources