在Rust中将`~str`编码为base64

lun*_*orn 2 base64 rust

我想~str在Rust中对base64 进行编码,以实现HTTP基本身份验证.

我找到了extra::base64,但我不明白应该如何使用它.该ToBase64特性似乎有一个实现&[u8],但编译器找不到它.以下测试程序:

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));
}
Run Code Online (Sandbox Code Playgroud)

在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));
                    ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Run Code Online (Sandbox Code Playgroud)

我错过了什么?

Vla*_*eev 7

ToBase64特性似乎有&[u8]的实现,但编译器找不到它.

实际上,编译器在代码中找不到它,因为您没有导入它.为了使用特征实现,您必须导入特征本身:

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));
}
Run Code Online (Sandbox Code Playgroud)

(我已经改为args()[0],args()[1]因为编码命令行参数而不是可执行名称更有趣:))

  • 注意,几天前,`extra :: base64`已被移动到`serialize :: base64`.您必须在代码中用`serialize'替换`extra`. (4认同)
  • 确定,但此信息对本网站的未来访问者有用. (3认同)