No method write found in TcpStream in rust [duplicate] - rust

I tried to compile the following program:
use std::io;
fn main() {
io::stdout().write(b"Please enter your name: ");
io::stdout().flush();
}
Unfortunately, compiler resisted:
error: no method named `write` found for type `std::io::Stdout` in the current scope
--> hello.rs:4:18
|
4 | io::stdout().write(b"Please enter your name: ");
| ^^^^^
|
= help: items from traits can only be used if the trait is in scope; the following trait is implemented but not in scope, perhaps add a `use` for it:
= help: candidate #1: `use std::io::Write`
I found that I needed to do use std::io::{self, Write};. What does use std::io; actually do then and how do (if possible) I pull all names defined in std::io? Also, would it be a bad style?

What does use std::io; actually do then?
It does what every use-statement does: makes the last part of the used path directly available (pulling it into the current namespace). That means that you can write io and the compiler knows that you mean std::io.
How do I pull all names defined in std::io?
With use std::io::*;. This is commonly referred to as glob-import.
Also, would it be a bad style?
Yes, it would. Usually you should avoid glob-imports. They can be handy for certain situations, but cause a lot of trouble on most cases. For example, there is also the trait std::fmt::Write... so importing everything from fmt and io would possibly result in name-clashes. Rust values explicitness over implicitness, so rather avoid glob-imports.
However, there is one type of module that is usually used with a glob-import: preludes. And in fact, there is even a std::io::prelude which reexports important symbols. See the documentation for more information.

Related

Is there a pattern to change compile behavior based on a type (proc macros)

I am trying to write a procedural macro that performs different behavior based on a trait type, which the macro may not have access to. For example, given the following trait:
trait Bar {
type BarType;
}
I would like to be able to change macro behavior based on the chosen BarType, even when my macro may not have direct access to it:
// This macro sees nothing about BarType
#[macro_option_1]
struct Foo {}
// this macro sees nothing about BarType
macro_option_2!(Foo);
// This location works but is not desirable
// #[working_macro_option]
impl Bar for Foo {
type BarType = Option<u32>;
}
A macro at working_macro_option would have access to BarType, but this location is not desirable (as my actual macro needs to work with multiple traits). So, my goal is to be able to use a macro that works at either macro_option_1 or macro_option_2, which have no useful content available to parse.
I am hoping for a pattern along the lines of what quote_spanned makes possible (link to example), but changing what the macro does in some way. So, I believe this needs to be something that's directly compilable, rather than something possible only in proc macros.
(this is unfortunately outside the scope of generics - my macro needs to create a function with a completely different signature based on type, for a C FFI)
Edit: more context on my end goal.
I am writing a library that helps users create a UDF, which is a dylib with a C interface. The init, process, add, remove etc. functions map nicely to traits (see my unfinished work here). My goal is that a user of my library can:
Define a struct or enum (which may be zero-sized, or contain something useful) which will give their UDF name
Implement my traits on this struct (one trait is required, the second is optional)
Add a #[register] macro to this struct
And from there, my library will generate the correct C interface functions via the macro. This isn't too different from how PyO3 works, I believe.
However, some of the C function signatures depend on the Return type within BasicUdf, so my macro needs some way to know what this is. I find it cleaner to put the macro on the main struct, so I am looking for a way to do this (hence this question)
My backup plan is to require placing the macro on the impl, which isn't terrible but is just less elegent (parsing the Returns type there is no problem). Something like a PhantomData marker on the main struct would also work, but I don't find that too ergonomic.

Where is checksumValid() defined?

I am working from a compliance perspective. I am struggling with the simplest thing, how to find the source for various functions that are called by rustup.
For example, the rustup source code references checksumValid, but I can't find it defined anywhere. I searched stackoverflow, I searched Google, etc.
I'd appreciate help finding checksumValid, but more importantly, what is wrong with my approach?
pub enum Notification<'a> {
...
NoUpdateHash(&'a Path),
ChecksumValid(&'a str),
SignatureValid(&'a str, &'a PgpPublicKey),
...
ChecksumValid(&'a str) here is not actually a function but rather one of many possible values of an enum Notification defined in this line. While the () is usually associated with functions in rust it can denote other things as well. In this case it denotes one possible value of the enum that contains some data that is of type &str with a lifetime of 'a. This is the definition of this value, in this line right here.
You might want to read this to understand the syntax.

In Rust, what kind of syntax is ::<Template>? [duplicate]

I read the below syntax from byteorder:
rdr.read_u16::<BigEndian>()
I can't find any documentation which explains the syntax instance.method::<SomeThing>()
This construct is called turbofish. If you search for this statement, you will discover its definition and its usage.
Although the first edition of The Rust Programming Language is outdated, I feel that this particular section is better than in the second book.
Quoting the second edition:
path::<...>, method::<...>
Specifies parameters to generic type, function, or method in an expression; often referred to as turbofish (e.g., "42".parse::<i32>())
You can use it in any kind of situation where the compiler is not able to deduce the type parameter, e.g.
fn main () {
let a = (0..255).sum();
let b = (0..255).sum::<u32>();
let c: u32 = (0..255).sum();
}
a does not work because it cannot deduce the variable type.
b does work because we specify the type parameter directly with the turbofish syntax.
c does work because we specify the type of c directly.

underscore in Rust: "consider using"

Rust newbie here.
When providing a parameter and leaving it unused in a function declaration (e.g. when learning Rust...) the compiler warns about the fact that the variable is unused in the scope, and proposes to consider putting an underline before it. Doing so, the warning disappears.
warning: unused variable: `y`
--> src/main.rs:23:29
|
23 | fn another_function(x: i32, y: i32) {
| ^ help: consider using `_y` instead
|
= note: #[warn(unused_variables)] on by default
why? How is the variable treated differently then?
It's just a convention: Rust doesn't emit a warning if a variable whose name starts with an underscore is not used because sometimes you may need a variable that won't be used anywhere else in your code.

How can structs in separate files reference each other?

Using structs that reference each other is common in a single file, but when I separate the structs into two files, I get an error.
mod_1.rs
mod mod_2;
use mod_2::Haha;
pub struct Hehe {
obj: Haha,
}
fn main() {
Hehe(Haha);
}
mod_2.rs
mod mod_1;
use mod_1::Hehe;
pub struct Haha {
obj: Hehe,
}
fn main() {
Haha(Hehe);
}
This will produce an error. When compiling the mod_1.rs:
error: cannot declare a new module at this location
--> mod_2.rs:1:5
|
1 | mod mod_1;
| ^^^^^
|
note: maybe move this module `mod_2` to its own directory via `mod_2/mod.rs`
--> mod_2.rs:1:5
|
1 | mod mod_1;
| ^^^^^
note: ... or maybe `use` the module `mod_1` instead of possibly redeclaring it
--> mod_2.rs:1:5
|
1 | mod mod_1;
| ^^^^^
When compiling the mod_2.rs:
error: cannot declare a new module at this location
--> mod_1.rs:1:5
|
1 | mod mod_2;
| ^^^^^
|
note: maybe move this module `mod_1` to its own directory via `mod_1/mod.rs`
--> mod_1.rs:1:5
|
1 | mod mod_2;
| ^^^^^
note: ... or maybe `use` the module `mod_2` instead of possibly redeclaring it
--> mod_1.rs:1:5
|
1 | mod mod_2;
| ^^^^^
In mod_1.rs I use something from mod_2.rs and in mod_2.rs, I use mod_1.rs's thing, so I'd like to find a way to get rid of the cycle reference module problem.
Trying to get Rust to load files is a similar but different problem.
This is a common misunderstanding of Rust's module system. Basically, there are two steps:
You have to build a module-tree. This implies that there are not cycles in this module-tree and there is a clear parent-child relationship between nodes. This step is simply to tell Rust what files to load and has nothing to do with usage of certain symbols in different modules.
You can now reference each symbol in your module tree by its path (where each module and the final symbol name is separated by ::, for example std::io::read). In order to avoid writing the full path every time, you can use use declarations to refer to specific symbols by their simple name.
You can read a bit more on that in the Rust book chapter.
And again, to avoid confusion: in order to use a symbol from a module, you don't necessarily have to write mod my_module; in your module! For each non-root module of your project there is only one line in your entire project saying mod said_module; (the root module does not have such a line at all). Only once!
About your example: you first compiled mod_1.rs via rustc mod_1.rs. This means that mod_1 is the root module in your case. As explained above, the root module doesn't need to be declared via mod at all, but all other modules need to be declared exactly once. This means the mod mod_2; in mod_1.rs is completely correct, but the mod mod_1; in mod_2.rs is incorrect. The compiler even suggest the right thing to do:
note: ... or maybe `use` the module `mod_2` instead of possibly redeclaring it
You are already useing it, so you can just remove the line mod mod_1; and solve this error.
However, I think you are still thinking incorrectly about the module system. As mentioned above you first need to design a more or less fixed module tree which implies that you have one fixed root module. Whatever you pass to rustc is the root module and it doesn't make sense to use different modules as root module. In your project there should be one fixed root module. This could be mod_1 as explained above. But it's usually more idiomatic to call it lib for libraries and main for executables.
So again: first, draw your module tree on a piece of paper. Consider this fixed for the moment and then you can create the files and mod declarations appropriately.
Last thing: even when fixing the module system, your example won't work, because Haha and Hehe are types with infinite size. Fields of structs are directly put into the memory layout of the struct (without boxing them like in Java!). Thus you can't have cycles in struct definitions, except if you manually add a layer of indirection, like boxing the fields. Please read this excellent explanation on this issue.

Resources