[英]Why does my code work when use std::io::Write is in my main but not when it's in my lib
I have two files I'm working with, main.rs and lib.rs.我有两个正在使用的文件,main.rs 和 lib.rs。
main.rs:主.rs:
use std::io;
use std::io::Write; //My library depends on this line :(
use input_macro_attempt::input;
fn main() {
let x = input!("Enter a variable: ");
println!("The variable is: {}", x);
}
lib.rs:库.rs:
use std::io;
use std::io::Write; //This one is irrelevant?
#[macro_export]
macro_rules! input{
($a:expr) =>{
{
print!("{}", $a);
std::io::stdout().flush().unwrap();
let mut input = String::new();
std::io::stdin().read_line(&mut input).unwrap();
input
}
};
(_) =>{{
let mut input = String::new();
std::io::stdin().read_line(&mut input).unwrap();
input
}
};
}
I've experimented but when I remove the use "std::io::Write" from main.rs my code breaks but why?我已经尝试过,但是当我从 main.rs 中删除使用“std::io::Write”时,我的代码中断了,但为什么呢?
I didn't like how the output came out with println.我不喜欢 output 是如何与 println 一起出现的。 so I switched to print!
所以我切换到打印! and manually flushed it so that you could put the input on the same line as the message.
并手动刷新它,以便您可以将输入与消息放在同一行。
Example: Enter the input: Your input示例:输入输入:您的输入
I add it to my lib.rs
and it doesn't make a difference, it only works if my main.rs
has it and I'm a little frustrated because in my lib it ignores the whole use term.我将它添加到我的
lib.rs
中,它没有什么区别,它只有在我的main.rs
有它时才有效,我有点沮丧,因为在我的 lib 中它忽略了整个使用术语。
In Rust as in other languages macro expansion is just a sort of text replacement mechanism, (well, ok Rust also checks token types etc but for your question we can ignore that) so you can think of input:("Enter a variable: ")
as being replaced with the contents of the macro at the call site.在 Rust 中,与其他语言一样,宏扩展只是一种文本替换机制,(好吧,Rust 也检查令牌类型等,但对于你的问题,我们可以忽略它)所以你可以想到
input:("Enter a variable: ")
在调用站点被替换为宏的内容。 If you want to use an include, you have to include it within the macro itself, not the module it's defined in.如果你想使用包含,你必须将它包含在宏本身中,而不是它定义的模块中。
#[macro_export]
macro_rules! input {
($a:expr) => {{
use ::std::io::Write;
print!("{}", $a);
::std::io::stdout().flush().unwrap();
let mut input = String::new();
::std::io::stdin().read_line(&mut input).unwrap();
input
}};
(_) => {{
use ::std::io::Write;
let mut input = String::new();
::std::io::stdin().read_line(&mut input).unwrap();
input
}};
}
I use ::
in front of the use
and other std
elements to guarantee I'm not accidentially including a submodule std
of the call site.我在
use
和其他std
元素之前使用::
来保证我不会意外地包含调用站点的子模块std
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.