수색…


통사론

  • <type> [] <name>;

비고

슬라이스는 기존 메모리에서 새로운 뷰를 생성합니다. 그들은 새로운 사본을 만들지 않습니다. 슬라이스에 더 이상 해당 메모리에 대한 참조 또는 슬라이스 된 부분이 없으면 가비지 수집기에서 해제됩니다.

슬라이스를 사용하면 예를 들어 하나의 메모리 블록에서 작동하는 파서 (parser)에 대해 매우 효율적인 코드를 작성하고 실제로 작업해야하는 부분을 슬라이스 할 수 있으므로 새로운 메모리 블록을 할당 할 필요가 없습니다.

선언과 초기화

import std.stdio;

void main() {
    int[] arr = [1, 2, 3, 4];

    writeln(arr.length); // 4
    writeln(arr[2]); // 3

    // type inference still works
    auto arr2 = [1, 2, 3, 4];
    writeln(typeof(arr2).stringof); // int[]
}

배열 연산

import std.stdio;

void main() {
    int[] arr = [1, 2, 3];

    // concatenate
    arr ~= 4;
    writeln(arr); // [1, 2, 3, 4]

    // per element operations
    arr[] += 10
    writeln(arr); // [11, 12, 13, 14]
}

조각

import std.stdio;

void main() {
    int[] arr = [1, 2, 3, 4, 5];
 
    auto arr2 = arr[1..$ - 1]; // .. is the slice syntax, $ represents the length of the array
    writeln(arr2); // [2, 3, 4]

    arr2[0] = 42;
    writeln(arr[1]); // 42
}


Modified text is an extract of the original Stack Overflow Documentation
아래 라이선스 CC BY-SA 3.0
와 제휴하지 않음 Stack Overflow