UFO ET IT

정수에서 문자열로 어떻게 변환합니까?

ufoet 2021. 1. 15. 07:41
반응형

정수에서 문자열로 어떻게 변환합니까?


유형을 정수에서 문자열로 변환하는 코드를 컴파일 할 수 없습니다. 다음 과 같은 다양한 유형 변환이 있는 Rust for Rubyists 튜토리얼 의 예제를 실행하고 있습니다.

"Fizz".to_str()num.to_str()(여기서는 num정수).

이러한 to_str()함수 호출 의 대부분 (모두는 아니지만) 이 더 이상 사용되지 않는다고 생각합니다 . 정수를 문자열로 변환하는 현재 방법은 무엇입니까?

내가 얻는 오류는 다음과 같습니다.

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`

사용하십시오 to_string()( 여기에서 예제 실행 ).

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

그리고 맞습니다 . 할당 된 문자열이 이제라고 부르기 때문에 일관성을 위해 Rust 1.0이 출시되기 전에 to_str()이름이 변경되었습니다 .to_string()String

어딘가에 문자열 슬라이스를 전달해야하는 경우에서 &str참조 를 얻어야합니다 String. 이는 &및 deref 강제를 사용하여 수행 할 수 있습니다 .

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

링크 한 튜토리얼이 더 이상 사용되지 않는 것 같습니다. Rust의 문자열에 관심이 있다면 The Rust Programming Language 의 문자열 장을 살펴볼 수 있습니다 .

참조 URL : https://stackoverflow.com/questions/24990520/how-do-i-convert-from-an-integer-to-a-string

반응형