Nim 語言程式教學:元組 (Tuple)

PUBLISHED ON MAR 14, 2018 — PROGRAMMING

    元組 (tuple) 的用途在於可在同一個複合型別中放入不同型別的元素。如下例:

    type
      Person = tuple[name: string, age: uint]
    
    var p: Person = (name: "Michael", age: 36U)
    assert(p.name == "Michael")
    assert(p.age == 36U)
    

    在本例中,我們建立一個 Person 型別,該型別由 nameage 兩個元素組成。

    我們在定義變數時,可忽略元素的名稱。如下例:

    type
      Person = tuple[name: string, age: uint]
    
    var p: Person = ("Michael", 36U)
    assert(p.name == "Michael")
    assert(p.age == 36U)
    

    但程式碼的可讀性會略差,較不建議。

    我們也可以建立一個匿名元組,如下例:

    var p: tuple[name: string, age: uint] = ("Michael", 36U)
    assert(p.name == "Michael")
    assert(p.age == 36U)
    

    我們還可以將元組解構 (destructuring),快速取出變數內容,如下例:

    from os import splitFile
    
    let path = "/home/user/file.txt"
    let (dir, name, ext) = splitFile(path)
    
    assert(dir == "/home/user")
    assert(name == "file")
    assert(ext == ".txt")
    
    TAGS: NIM, NIM 語法, TUPLE
    comments powered by Disqus