Why do I need to import a characteristic in order to use the methods that it defines for the type?

I have a very simple Rust code example that does not compile:

extern crate rustc_serialize; use rustc_serialize::base64; fn main() { let auth = format!("{}:{}", "user", "password"); let auth_b64 = auth.as_bytes().to_base64(base64::MIME); println!("Authorization string: {}", auth_b64); } 

Compiler Error:

 error[E0599]: no method named `to_base64` found for type `&[u8]` in the current scope --> src/main.rs:6:36 | 6 | let auth_b64 = auth.as_bytes().to_base64(base64::MIME); | ^^^^^^^^^ | = help: items from traits can only be used if the trait is in scope = note: the following trait is implemented but not in scope, perhaps add a `use` for it: candidate #1: `use rustc_serialize::base64::ToBase64;` 

It works if I import the trait explicitly:

 extern crate rustc_serialize; use rustc_serialize::base64::{self, ToBase64}; fn main() { let auth = format!("{}:{}", "user", "password"); let auth_b64 = auth.as_bytes().to_base64(base64::MIME); println!("Authorization string: {}", auth_b64); } 

Why do I need to use rustc_serialize::base64::ToBase64; ?

+6
source share
1 answer

It is just as it is. In Rust, a trait should be within the scope of a method call.

In this regard, the cause of the collision is the cause. All formatting characters in std::fmt ( Display , Debug , LowerHex , & c.) Have the same method signature for fmt . For instance; What would object.fmt(&mut writer, &mut formatter) do, for example? Rusts answers - "you must explicitly indicate if you have a trait in the area where this method is."

Notice also how the error message states that a "no method named` m "was found for type` T` in the current scope.

+7
source

Source: https://habr.com/ru/post/973724/


All Articles