Reputation: 54793
In Rust programming language - I am trying to convert an integer into the string representation and so I write something like:
use std::int::to_str_bytes;
...
to_str_bytes(x, 10);
...but it says that I have to specify a third argument.The documentation is here: http://static.rust-lang.org/doc/master/std/int/fn.to_str_bytes.html , but I am not clever enough to understand what it expects as the third argument.
Upvotes: 3
Views: 490
Reputation: 3541
Using x.to_str()
as in Njol's answer is the straightforward way to get a string representation of an integer. However, x.to_str()
returns an owned (and therefore heap-allocated) string (~str
). As long as you don't need to store the resulting string permanently, you can avoid the expense of an extra heap allocation by allocating the string representation on the stack. This is exactly the point of the std::int::to_str_bytes
function - to provide a temporary string representation of a number.
The third argument, of type f: |v: &[u8]| -> U
, is a closure that takes a byte slice (I don't think Rust has stack-allocated strings). You use it like this:
let mut f = std::io::stdout();
let result = std::int::to_str_bytes(100, 16, |v| {
f.write(v);
Some(())
});
to_str_bytes
returns whatever the closure does, in this case Some(())
.
Upvotes: 4
Reputation: 3279
int seems to implement ToStr: http://static.rust-lang.org/doc/master/std/to_str/trait.ToStr.html
so you should be able to simply use x.to_str()
or to_str(x)
Upvotes: 1