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.
Related
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.
I would like to add suffixes to the name of file modules
module1/
- mod.rs
- module.suffix1.rs
- module.suffix2.rs
- module.suffix3.rs
main.rs
// module1/mod.rs
pub use module.seuffix1;
^ Error
pub use module.suffix2;
^ Error
pub use module.suffix3;
^ Error
How can I achieve this?
P.S. I'm not sure if this convention is "okay" in rust, but module_suffix2.rs looks messy when a file name consists of two words - my_modyle_suffix.rs
You cannot include dots in names. You can create a module module and have suffix, suffix2 and suffix3 as submodules, accessing them with module::suffix. If you prefer to keep the directory structure flat, you can use the #[path] attribute.
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.
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.
This question already has answers here:
Use of undeclared type or module `std` when used in a separate module
(2 answers)
Closed 6 years ago.
I'm trying to read a single character from stdin, but I can't get it working. In different program, I used this exact same method and it worked.
let mut buffer = [0];
let _ = std::io::stdin().read(&mut buffer);
let a = buffer[0];
Compiling it gives this error:
src/befunge.rs:220:17: 220:31 error: failed to resolve. Use of undeclared type or module `std::io` [E0433]
src/befunge.rs:220 let _ = std::io::stdin().read(&mut buffer);
I assume that befunge.rs is not your crate root, but a submodule. Paths like std::io::stdin() that are used outside of a use ...; declaration are relative to the current module, not absolute. To make the path absolute, prefix :: (like a prefixed / in unix paths) -> ::std::io::stdin(). Alternatively you can use some part of the path, like:
use std;
std::io::stdin();
or
use std::io;
io::stdin();
If you are using a subpath, like std::io more than once in your module, it's usually best to use it at the top.
If you are in the crate root, there is no difference between ::std and std, because the relative lookup path is the root. It only matters in submodules. Also: paths in use declarations are always absolute -- to make them relative to the current module prefix self::.