There are some situations where stderr is not available. Is there a way to have dbg!() print to stdout or an alternative command that prints the same information as dbg!() to stdout?
For an alternative command, copy-and-paste the implementation of dbg, changing eprintln to println and $crate to ::std:
macro_rules! dbg {
// NOTE: We cannot use `concat!` to make a static string as a format argument
// of `println!` because `file!` could contain a `{` or
// `$val` expression could be a block (`{ .. }`), in which case the `println!`
// will be malformed.
() => {
::std::println!("[{}:{}]", ::std::file!(), ::std::line!())
};
($val:expr $(,)?) => {
// Use of `match` here is intentional because it affects the lifetimes
// of temporaries - https://stackoverflow.com/a/48732525/1063961
match $val {
tmp => {
::std::println!("[{}:{}] {} = {:#?}",
::std::file!(), ::std::line!(), ::std::stringify!($val), &tmp);
tmp
}
}
};
($($val:expr),+ $(,)?) => {
($(::std::dbg!($val)),+,)
};
}
fn main() {
dbg!(1 + 1);
}
Related
I want to test every value an observable emits, and if it fits certain criteria, then error-out the result, otherwise pass the value on. Is there an operator for this?
If you use throw, you can separate cases that do not match the condition, but they will terminate immediately.
let source = Observable.of(1,2,3);
source
.mergeMap(value => {
if (value > 1) { // condition
return Observable.throw(`Out Of Condition: ${value}`);
}
return Observable.of(value);
})
.subscribe(
value => console.log(`Next: ${value}`),
error => console.log(`Error: ${error}`),
() => console.log('completed')
);
Result:
Next: 1
Error: Out Of Condition: 2
You can also think of ways like stdout and stderr in bash. For this, additional information was augmented. In this case, it does not end in the middle.
const stdout = 1;
const stderr = 2;
let source = Observable.of(1,2,3);
source
.map(value => {
if (value > 1) { // condition
return [stderr, value];
}
return [stdout, value];
})
.subscribe(channel_value => {
let channel = channel_value[0];
let value = channel_value[1];
if (channel == stdout) {
console.log(`stdout: ${value}`);
}
else if (channel == stderr) {
console.log(`stderr: ${value}`);
}
});
Result:
stdout: 1
stderr: 2
stderr: 3
I don't know if this is the right answer, but what worked for me, was Observable.create
Observable.create((observer: Observer) =>
sourceObservable.subscribe((val: Value) => {
if(condition)
observer.next(val);
else
observer.error(val);
}, observer.error, observer.complete)
)
This is very inelegant. I hope there is a better way
I read that using unwrap on a Result is not a good practice in Rust and that it's better to use pattern matching so any error that occurred can be handled appropriately.
I get the point, but consider this snippet that reads a directory and prints the accessed time for each entry:
use std::fs;
use std::path::Path;
fn main() {
let path = Path::new(".");
match fs::read_dir(&path) {
Ok(entries) => {
for entry in entries {
match entry {
Ok(ent) => {
match ent.metadata() {
Ok(meta) => {
match meta.accessed() {
Ok(time) => {
println!("{:?}", time);
},
Err(_) => panic!("will be handled")
}
},
Err(_) => panic!("will be handled")
}
},
Err(_) => panic!("will be handled")
}
}
},
Err(_) => panic!("will be handled")
}
}
I want to handle every possible error in the code above (the panic macro is just a placeholder). While the code above works, I think it's ugly. What is the idiomatic way to handle a case like this?
I read that using unwrap on a Result is not a good practice in Rust.
It's not that easy. For example, read my answer here to learn a bit more. Now to your main problem:
Reduce right shift by passing Ok value to the outside
One big issue with your code is the right shift: for example, the meta.accessed() call is indented a whole lot. We can avoid this by passing the value we want to work with out of the match:
let entries = match fs::read_dir(&path) {
Ok(entries) => entries, // "return" from match
Err(_) => panic!("will be handled"),
};
for entry in entries { // no indentation! :)
// ...
}
That's already a very good way to make the code more readable.
Using the ? operator to pass the error to the calling function
Your function could return a Result<_, _> type in order to pass the error to the calling function (yes, even main() can return Result). In this case you can use the ? operator:
use std::{fs, io};
fn main() -> io::Result<()> {
for entry in fs::read_dir(".")? {
println!("{:?}", entry?.metadata()?.accessed()?);
}
Ok(())
}
Use helper methods of Result
There are also many helper methods, like map() or and_then(), for the Result type. and_then is helpful if you want to do something, if the result is Ok and this something will return a result of the same type. Here is your code with and_then() and manual handling of the error:
fn main() {
let path = Path::new(".");
let result = fs::read_dir(&path).and_then(|entries| {
for entry in entries {
let time = entry?.metadata()?.accessed()?;
println!("{:?}", time);
}
Ok(())
});
if let Err(e) = result {
panic!("will be handled");
}
}
There really isn't only one way to do this kind of error handling. You have to get to know all the tools you can use and then need to choose the best for your situation. However, in most situations, the ? operator is the right tool.
Result happens to have a lot of convenience methods for these kinds of things:
use std::fs;
use std::path::Path;
fn main() {
let path = Path::new(".");
match fs::read_dir(&path) {
Ok(entries) => {
for entry in entries {
match entry.and_then(|e| e.metadata()).map(|m| m.accessed()) {
Ok(time) => {
println!("{:?}", time);
},
Err(_) => panic!("will be handled")
}
}
},
Err(_) => panic!("will be handled")
}
}
And usually you will not have so much logic in main and will simply be able to use ? or try! in another function:
use std::fs;
use std::path::Path;
fn print_filetimes(path: &Path) -> Result<(), std::io::Error> {
for entry in fs::read_dir(&path)? {
let time = entry.and_then(|e| e.metadata()).map(|m| m.accessed())?;
println!("{:?}", time);
}
Ok(())
}
fn main() {
let path = Path::new(".");
match print_filetimes(path) {
Ok(()) => (),
Err(_) => panic!("will be handled"),
}
}
Is it possible to directly modify a value embedded inside an enum?
The following fails with error: cannot borrow immutable anonymous field `a.0` as mutable, even though I used ref mut.
enum Foo {
Bar(usize),
}
fn main() {
let a = Foo::Bar(10);
match a {
Foo::Bar(ref mut val) => *val = 33,
}
match a {
Foo::Bar(val) => println!("{}", val), // should print 33
}
}
That's not a huge problem because I can do the following as a work-around:
match a {
Foo::Bar(val) => a = Foo::Bar(33),
}
But is this the correct way?
You need to make the binding to a mutable.
enum Foo {
Bar(usize),
}
fn main() {
let mut a = Foo::Bar(10);
match a {
Foo::Bar(ref mut val) => *val = 33,
}
match a {
Foo::Bar(val) => println!("{}", val), // 33
}
}
How to do something similar to this D and Java code in Rust?
Java:
import java.nio.file.*;
import java.io.*;
public class Main {
public static void main( String[] args ) throws IOException
{
Files.lines(Paths.get("/home/kozak/test.txt"))
.filter(s -> s.endsWith("/bin/bash"))
.map(s -> s.split(":", 2)[0])
.forEach(System.out::println);
}
}
D language:
import std.algorithm;
import std.stdio;
void main() {
File("/home/kozak/test.txt")
.byLine
.filter!((s)=>s.endsWith("/bin/bash"))
.map!((s)=>s.splitter(":").front)
.each!writeln;
}
I try it, but I am lost with all this ownership stuff
my rust code:
use std::io::BufReader;
use std::fs::File;
use std::io::BufRead;
use std::io::Lines;
fn main() {
let file = match File::open("/etc/passwd") {
Ok(file) => file,
Err(..) => panic!("room"),
};
let mut reader = BufReader::new(&file);
for line in reader.lines().filter_map(
|x| if match x { Ok(v) => v.rmatches("/bin/bash").count() > 0, Err(e) => false}
{ match x { Ok(v2) => Some(v2.split(":").next()), Err(e2) => None }} else
{ None })
{
print!("{}", line.unwrap() );
}
}
Here you go:
use std::fs::File;
use std::io::{BufRead, BufReader};
fn main() {
let f = BufReader::new(File::open("/etc/passwd").unwrap());
let it = f.lines()
.map(|line| line.unwrap())
.filter(|line| line.ends_with("/bin/bash"))
.map(|line| line.split(":").next().unwrap().to_owned());
for p in it {
println!("{}", p);
}
}
This code allocates a separate string for each first splitted part though, but I don't think it is possible to avoid it without streaming iterators. And, of course, error handling here is really lax.
I guess an imperative approach would be more idiomatic, especially in regard to error handling:
use std::fs::File;
use std::io::{BufRead, BufReader};
fn main() {
let f = BufReader::new(File::open("/etc/passwd").unwrap());
for line in f.lines() {
match line {
Ok(line) => if line.ends_with("/bin/bash") {
if let Some(name) = line.split(":").next() {
println!("{}", name);
} else {
println!("Line does not contain ':'");
}
},
Err(e) => panic!("Error reading file: {}", e)
}
}
}
I'm diving into rust, and I'm trying to do something like this:
match send("select * from User;") {
ConnError => println!("Connection error!"),
DBError(e) => println!("Database error {}", e),
Ok(response) => {
...
}
}
and I'm trying to figure out a compact way of defining the send function. I saw the Result enum, but it only handles one kind of error at a time. I was hoping that I could define my own enum like this:
fn send(query: str) -> enum { Ok(Box<Response>), ConnError, DBError(str) } {
...
}
alas, it is not possible, it's complaining about the unexpected 'enum' keyword. Is there any way to do what I'm trying here, or perhaps make Result handle multiple error types? Thanks!
As you say, you can use Result but you have to define the enum with your error types separately, as you can't define it directly in the return of your function.
Something like this:
use std::rand::distributions::{IndependentSample, Range};
fn main() {
match send("select * from foo") {
Ok(Response) => println!("response"),
Err(e) => match e {
ConnError => println!("connection error"),
DbError(err) => println!("{}", err)
}
}
}
// the enum with your errors
enum DataLayerError {
ConnError,
DbError(String)
}
struct Response; /*...*/
fn send(_query: &str) -> Result<Response, DataLayerError> {
let between = Range::new(0u, 2);
let mut rng = std::rand::task_rng();
// return a random result
match between.ind_sample(&mut rng) {
0 => Ok(Response),
1 => Err(DbError("yikes".to_string())),
2 => Err(ConnError),
_ => unreachable!()
}
}