On two different #[cfg] name is defined multiple times

Hi there,

I'm doing this:

#[cfg(feature = "tls-rust")]
use tokio_rustls::{client::TlsStream, TlsConnector as TokioTlsConnector};
#[cfg(feature = "tls-native")]
use tokio_tls::{TlsConnector as TokioTlsConnector, TlsStream};

and the compiler is complaining about TokioTlsConnector being defined multiple times:

error[E0252]: the name `TokioTlsConnector` is defined multiple times                                  
  --> src\conn.rs:36:17
   |
34 | use tokio_rustls::{client::TlsStream, TlsConnector as TokioTlsConnector};
   |                                       --------------------------------- previous import of the type `TokioTlsConnector` here
35 | #[cfg(feature = "tls-native")]
36 | use tokio_tls::{TlsConnector as TokioTlsConnector, TlsStream};
   |                 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ `TokioTlsConnector` reimported here
   |
   = note: `TokioTlsConnector` must be defined only once in the type namespace of this module
help: you can use `as` to change the binding name of the import
   |
36 | use tokio_tls::{TlsConnector as OtherTokioTlsConnector, TlsStream};
   |                 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Why is that? Isn't #[cfg] conditional compilation?

Cargo features are additive, and can't be mutually-exclusive. It's possible for all features to be enabled at the same time.

Try using #[cfg(feature = "tls-rust")] and #[cfg(not(feature = "tls-rust"))] instead of two features.

1 Like

Thank you for your answer :slight_smile:
can this work?

#[cfg(all(feature = "tls-rust", not(feature = "tls-native")))]
use tokio_rustls::{client::TlsStream, TlsConnector as TokioTlsConnector};
#[cfg(all(feature = "tls-native", not(feature = "tls-rust")))]
use tokio_tls::{TlsConnector as TokioTlsConnector, TlsStream}; 

I tried it but it seems that it can't find TokioTlsConnector anymore

Your code fails if BOTH tls-rust and tls-native are enabled. You can't prevent that from happening. It's normal in Cargo to enable ALL features (e.g. cargo build --all-features)

Cargo does not support either/or features. You can't rely on having either one or the other feature enabled only. You are forced to support a case when both are selected at the same time.

2 Likes

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.