web-dev-qa-db-fra.com

Comment convertir char en chaîne?

Cette question concerne une version préliminaire de Rust.
Cette question plus jeune est similaire.


J'ai essayé d'imprimer un symbole par io::println fonction

fn main() {
    io::println('c');
}

Mais j'ai eu la prochaine erreur:

$ rustc pdst.rs 
pdst.rs:2:16: 2:19 error: mismatched types: expected `&str` but found `char` (expected &str but found char)
pdst.rs:2     io::println('c');
                          ^~~
error: aborting due to previous error

Comment convertir char en chaîne?

[~ # ~] mise à jour [~ # ~]

Le transtypage direct ne fonctionne pas:

let text:str = 'c';
let text:&str = 'c';
let text:@str = 'c';
let text:~str = 'c';

Il renvoie:

pdst.rs:7:13: 7:16 error: bare `str` is not a type
pdst.rs:7     let text:str = 'c';
                       ^~~
pdst.rs:7:19: 7:22 error: mismatched types: expected `~str` but found `char` (expected ~str but found char)
pdst.rs:7     let text:str = 'c';
                             ^~~
pdst.rs:8:20: 8:23 error: mismatched types: expected `&str` but found `char` (expected &str but found char)
pdst.rs:8     let text:&str = 'c';
                              ^~~
pdst.rs:9:20: 9:23 error: mismatched types: expected `@str` but found `char` (expected @str but found char)
pdst.rs:9     let text:@str = 'c';
                              ^~~
pdst.rs:10:20: 10:23 error: mismatched types: expected `~str` but found `char` (expected ~str but found char)
pdst.rs:10     let text:~str = 'c';
                               ^~~
error: aborting due to 5 previous errors
33
Denis Kreshikhin

Utilisation char::to_string, ce qui est étrangement non documenté :

fn main() {
    io::println('c'.to_string());
}
36
Hubro

Vous pouvez maintenant utiliser c.to_string(), où c est votre variable de type char.

17
Rory