Question

I'd like to encode a ~str to base64 in Rust, to implement HTTP Basic Authentication.

I found extra::base64, but I don't get how it's supposed to be used. The ToBase64 trait seems to have an implementation for &[u8], but it's not found by the compiler. The following test program:

extern mod extra;

fn main() {
    use extra::base64::MIME;

    let mut config = MIME;
    config.line_length = None;
    let foo = ::std::os::args()[0];
    print(foo.as_bytes().to_base64(config));
}

fails with the following error on Rust 0.9:

rustc -o test test.rs
test.rs:9:11: 9:44 error: type `&[u8]` does not implement any method in scope named `to_base64`
test.rs:9     print(foo.as_bytes().to_base64(config));
                    ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

What am I missing?

Was it helpful?

Solution

The ToBase64 trait seems to have an implementation for &[u8], but it's not found by the compiler.

Indeed, it is not found by the compiler in your code because you're not importing it. In order to use trait implementations, you have to import the trait itself:

extern mod extra;

fn main() {
    use extra::base64::{ToBase64, MIME};

    let mut config = MIME;
    config.line_length = None;
    let foo = ::std::os::args()[1];
    print(foo.as_bytes().to_base64(config));
}

(I've changed args()[0] to args()[1] since it is more interesting to encode command line arguments instead of executable name only :))

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top