167

I am unable to compile code that converts a type from an integer to a string. I'm running an example from the Rust for Rubyists tutorial which has various type conversions such as:

"Fizz".to_str() and num.to_str() (where num is an integer).

I think the majority (if not all) of these to_str() function calls have been deprecated. What is the current way to convert an integer to a string?

The errors I'm getting are:

error: type `&'static str` does not implement any method in scope named `to_str`
error: type `int` does not implement any method in scope named `to_str`
Rakete1111
  • 47,013
  • 16
  • 123
  • 162
user3358302
  • 1,871
  • 2
  • 11
  • 10
  • sorry if I don't follow but i've tried looking up the int source and it seems to use http://doc.rust-lang.org/0.11.0/std/num/strconv/index.html but this just returns a byte vector. In addition there is the `to_string()` method but that returns `String` and not a literal string. – user3358302 Jul 28 '14 at 08:16
  • haha nevermind, I thought `to_str()` was a different return value, I'll use `to_string()` – user3358302 Jul 28 '14 at 08:30
  • 1
    @user3358302, no method can return a thing you call "literal string" unless they do return statically known literals because these values have type `&'static str`, that is, a string slice with a static lifetime, which is impossible to obtain using dynamically created data. You can only create them using string literals. – Vladimir Matveev Jul 28 '14 at 08:33
  • good to know! I think the method `to_str` confused me (which as you said, they renamed for clarity) thinking it was returning a string slice instead of a `String` object. – user3358302 Jul 28 '14 at 08:37

1 Answers1

227

Use to_string() (running example here):

let x: u32 = 10;
let s: String = x.to_string();
println!("{}", s);

You're right; to_str() was renamed to to_string() before Rust 1.0 was released for consistency because an allocated string is now called String.

If you need to pass a string slice somewhere, you need to obtain a &str reference from String. This can be done using & and a deref coercion:

let ss: &str = &s;   // specifying type is necessary for deref coercion to fire
let ss = &s[..];     // alternatively, use slicing syntax

The tutorial you linked to seems to be obsolete. If you're interested in strings in Rust, you can look through the strings chapter of The Rust Programming Language.

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Vladimir Matveev
  • 120,085
  • 34
  • 287
  • 296
  • 1
    Thanks a lot man, this clears things up :) Also i'll go through that tutorial since string conversion seems like something that's still changing on rust. – user3358302 Jul 28 '14 at 08:37