Programing

여러 줄 문자열 리터럴의 구문은 무엇입니까?

crosscheck 2020. 9. 7. 07:40
반응형

여러 줄 문자열 리터럴의 구문은 무엇입니까?


Rust에서 문자열 구문이 어떻게 작동하는지 알아내는 데 어려움을 겪고 있습니다. 특히, 여러 줄 문자열을 만드는 방법을 알아 내려고합니다.


모든 문자열 리터럴은 여러 줄로 나눌 수 있습니다.

let string = "line one
line two";

두 줄의 문자열로, 다음과 같습니다 "line one\nline two"(물론 \n개행 이스케이프를 직접 사용할 수도 있습니다). 그냥 이유를 포맷하는 여러 줄에 걸쳐 문자열을 중단하고자하는 경우 당신은 함께 줄 바꿈과 최고의 공백 탈출 할 수 \, 예를

let string = "one line \
    written over \
    several";

와 동일합니다 "one line written over several".


따옴표, 백 슬래시 등을 포함하거나 포함하지 않을 수있는 조금 더 긴 작업을 수행하려면 원시 문자열 리터럴 표기법을 사용하십시오 .

let shader = r#"
    #version 330

    in vec4 v_color;
    out vec4 color;

    void main() {
        color = v_color;
    };
"#;

문자열 내에 일련의 큰 따옴표와 해시 기호가있는 경우 임의의 수의 해시를 구분 기호로 나타낼 수 있습니다.

let crazy_raw_string = r###"
    My fingers #"
    can#"#t stop "#"" hitting
    hash##"#
"###;

Huon의 대답 은 정확하지만 들여 쓰기가 귀찮다면 들여 쓰기 된 여러 줄 문자열에 대한 절차 매크로 인 Indoc사용 하는 것이 좋습니다. "들여 쓰기 된 문서"를 의미합니다. 여러 indoc!()줄 문자열 리터럴을 받아 들여 쓰기를 해제하는 라는 매크로를 제공 하여 가장 왼쪽의 공백이 아닌 문자가 첫 번째 열에 있습니다.

let s = indoc!("
          line one
          line two");

결과는 "line one\nline two"입니다.

원하는 경우 동일한 형식을 지정하는 몇 가지 동등한 방법이 있으므로 원하는 것을 선택하십시오. 다음 둘 다 위와 같은 문자열이됩니다. 콘텐츠는 원하는만큼 들여 쓸 수 있습니다. 특정 개수의 공백이 아니어도됩니다.

let s = indoc!(
         "line one
          line two");

let s = indoc!("line one
                line two");

Whitespace is preserved relative to the leftmost non-space character in the document, so the following has line two indented 3 spaces relative to line one:

let s = indoc!("
          line one
             line two");

The result is "line one\n line two".


In case you want to indent multiline text in your code:

let s = "first line\n\
    second line\n\
    third line";

println!("Multiline text goes next:\n{}", s);

The result will be the following:

Multiline text goes next:
first line
second line
third line

참고URL : https://stackoverflow.com/questions/29483365/what-is-the-syntax-for-a-multiline-string-literal

반응형