I want to play with BasicAuth stuff, therefore I need the base64 version of a string. So I needed a function : String to base_64(String).
In the string guides for Rust, most of the time $str is preferred to String. So I wanted to adjust to this idea.
But working with &str is somehow harder than it seems (I know that my problem is related to Question also about as_slice()).
The author of other question could solve his problem by not using as_slice(), is there a way to still work with &str for me?
extern crate serialize;
use serialize::base64::{ToBase64,MIME};
fn generate_base_string (n : &str) -> String {
let mut config = serialize::base64::MIME;
config.line_length = None;
let bytes: & [u8] = n.as_bytes();
return bytes.to_base64(config);
}
fn generate_base<'a> (n : &'a str ) -> &'a str {
let mut config = serialize::base64::MIME;
config.line_length = None;
let bytes: & [u8] = n.as_bytes();
let res2: String = bytes.to_base64(config);
let res1: &'a str = res2.as_slice();
return res1;
}
#[test]
fn right_base64() {
let trig :&str = generate_base("string");
assert!(trig=="c3RyaW5n");
}
// http://doc.rust-lang.org/guide-strings.html
#[test]
fn right_base64_string(){
// A `String` - a heap-allocated string
assert!(generate_base_string("string")=="c3RyaW5n".to_string());
}
These are my first baby steps in Rust so please be not to mean if I do something really wrong.
&
is a pointer, it points to a memory that somebody else owns.
So, &str
is a pointer to a string memory (slice) that somebody else owns.
String
, on the other hand, is a string that owns its memory and keeps the characters there.
Now, when you generate a base64 you make something new, it's like hearing a piano concerto and catching it in an oil painting. Instead of taking your brush and making the painted version of the concerto you could just point to the original music, but that won't work when you specifically need a painted version. Similarly simply pointing to the original string won't work when you need a base64 version. You need to make something new, you need a canvas for it, that is the String
.
What you're trying to do in fn generate_base<'a> (n : &'a str ) -> &'a str
is akin to creating a painting, destroying it and pointing to the destroyed painting. Look at the painting I made!.. only I've burned it. That's against the Rust safety rules, you shouldn't point to something which no longer exists (it's also known as a "dangling pointer").
String
is not evil, don't be afraid to use a new String
when you're creating something new.
But why people avoid String
? It's because passing String
is like passing the real painting. Imagine a museum taking the Leonardo from the wall and giving it to you: here, take it for a walk, enjoy. Now that you've taken it, nobody else will see it in the museum. And you'll have to give it back. It's often easier to simply visit the museum and look at the thing, without moving it anywhere.