1

I'm trying to setup tracing and I have this code but it compiles with errors:

use tracing_subscriber; pub fn init(is_pretty: bool) { let subscriber = tracing_subscriber::fmt(); if is_pretty { &subscriber.pretty(); } subscriber.init(); } 
error[E0382]: use of moved value: `subscriber` --> src\main.rs:8:5 | 4 | let subscriber = tracing_subscriber::fmt(); | ---------- move occurs because `subscriber` has type `SubscriberBuilder`, which does not implement the `Copy` trait 5 | if is_pretty { 6 | &subscriber.pretty(); | -------- `subscriber` moved due to this method call 7 | } 8 | subscriber.init(); | ^^^^^^^^^^ value used here after move 

I tried this too but I get different compiler errors:

use tracing_subscriber; pub fn init(is_pretty: bool) { let mut subscriber = tracing_subscriber::fmt(); if is_pretty { subscriber = subscriber.pretty(); } subscriber.init(); } 
error[E0308]: mismatched types --> src\main.rs:6:22 | 4 | let mut subscriber = tracing_subscriber::fmt(); | ------------------------- expected due to this value 5 | if is_pretty { 6 | subscriber = subscriber.pretty(); | ^^^^^^^^^^^^^^^^^^^ expected struct `DefaultFields`, found struct `Pretty` | = note: expected struct `SubscriberBuilder<DefaultFields, Format<tracing_subscriber::fmt::format::Full>>` found struct `SubscriberBuilder<Pretty, Format<Pretty>>` 

How can I fix this?

1 Answer 1

3

SubscriberBuilder encodes in its type the various options used to build the subscriber, so the only way to go would be:

if is_pretty { tracing_subscriber::fmt() .with_env_filter("info") .pretty() .init(); } else { tracing_subscriber::fmt() .with_env_filter("info") .init(); } 

The fact is that this builder was probably thought to have "hard-coded" configuration.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks. I tried the second way but I still have issues: mismatched types expected struct tracing_subscriber::fmt::SubscriberBuilder<tracing_subscriber::fmt::format::DefaultFields, tracing_subscriber::fmt::format::Format<tracing_subscriber::fmt::format::Full>, _>` found struct tracing_subscriber::fmt::SubscriberBuilder<tracing_subscriber::fmt::format::Pretty, tracing_subscriber::fmt::format::Format<tracing_subscriber::fmt::format::Pretty>, _>rustcE0308 tracing.rs(12, 26): expected due to this value`
If I try the first way you're suggesting the error is: "if" and "else" have incompatible types rustc E0308
@FredHors I updated my answer. There would be a way around to remove code duplication using traits, but I felt it's a bit overkill (it wouldn't reduce the amount of code written anyways), so I left it out.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.