본문 바로가기
Zig

[Zig] 지연(defer)

by 코드쉼터 2024. 3. 20.

Zig 에서 지연은 해당 코드의 실행을 중괄호(scope) 마지막에서 수행되도록 미룹니다.

---------------------------------------------------------------------------------------------------

 {

    defer 맨 마지막에 수행되도록 미룰 코드

    // 다른 코드들...

 }

 

메모리 할당 바로 아래 defer 키워드로 소멸을 같이 명시하면 코드의 가독성이 높아집니다.

중괄호 내에서 defer 표현식이 여러번 등장한 경우, 역순으로 수행됩니다. (내부적으로 스택에 쌓임)

---------------------------------------------------------------------------------------------------

 

예시

// 긴 코드 내에서 닫는 괄호를 까먹지 않도록 미리 적어두면 읽기 편합니다.

fn printAnimal(animal : u8) void 
{
    std.debug.print( " ( " ,  .{} );

    defer std.debug.print( " ) " ,  .{} ); // 이렇게 닫는 괄호를 까먹지 않도록 미리 적어둘 수 있습니다.

 

    // 아래 내용을 엄청나게 긴 코드라고 가정합니다.
    if (animal == 'g') 
    {
        std.debug.print("Goat", .{});
        return;
    }
    if (animal == 'c') 
    {
        std.debug.print("Cat", .{});
        return;
    }
    if (animal == 'd') 
    {
        std.debug.print("Dog", .{});
        return;
    }

    std.debug.print("Unknown", .{});
}

// 실행 예 : " ( Goat ) "

 

 

 

예시

// 파일의 open 과 close 를 같이 적어두면 편합니다.

pub fn readBytes(allocator: std.mem.Allocator, path: []const u8, len: usize) ![]u8

{
    // Open file.
    const file = try std.fs.cwd().openFile(path, .{});
    defer file.close(); // 파일을 열었다면 다 사용하고 나서 까먹지 말고 닫아야 합니다.

    // Create a buffer for reading.
    var list = try std.ArrayList(u8).initCapacity(allocator, len);
    var buffer = list.allocatedSlice();

    // Read the file and return the read bytes.
    const bytes_read = try file.read(buffer);
    return buffer[0..bytes_read];

    

    // 맨 마지막에 file.close(); 가 수행됩니다.
}

 

 

 

'Zig' 카테고리의 다른 글

[Zig] 도달 불가능(unreachable)  (0) 2024.03.21
[Zig] switch 조건문(statement)  (0) 2024.03.21
[Zig] 에러(errors)  (0) 2024.03.20
[Zig] 함수(functions)  (0) 2024.03.20
[Zig] for 반복문(loop)  (0) 2024.03.20