let a: &str = "123";
let b: i32 = 123;
how to cast i32 to &str?
let a: &str = "123";
let b: i32 = 123;
how to cast i32 to &str?
There's a method called to_string
which will convert it to a String
.
let a: i32 = 123;
let b = a.to_string();
whether it can be type: &str ?
let b = a.to_string(); it's String.
A reference to String
is automatically converted to &str
by the compiler. So you can do this:
fn takes_str(value: &str) {
println!("Value is: {}", value);
}
fn main() {
let a: i32 = 123;
let b = a.to_string();
takes_str(&b);
}
If you want the conversion to &str
to be explicit, then you can also call String::as_str
.
fn main() {
let a: i32 = 123;
let b = a.to_string();
takes_str(b.as_str());
}
really perfect, thanks so much.
This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.