# 匹配

## match语句

match语句是`if-else`的简写方法。 如果输入匹配，将执行第一个匹配分支的语句块，并返回其最后一个表达式。 `else`分支将在没有其他匹配分支时执行。

```
num := 1
match num % 2 == 0  {
    true { print('The input number is even.') }
    else { print('The input number is odd.') }
}
```

还可以使用`match`初始化变量，以便根据条件具有不同的值。

```
num := 3
s := match num {
    1 { 'one' }
    2 { 'two' }
    else {
        'many'
    }
}
```

例如:

```
fn even(num int) bool {
    match num % 2 == 0  {
        true { print('The input number is even.') }
        else { print('The input number is odd.') }
    }
}

fn num_to_str(num int) int {
    match num {
        1 { 'one' }
        2 { 'two' }
        else {
            'many'
        }
    }
}

fn main() {
    println(even(14))           // 'The input number is even.'
    println(even(3))            // 'The input number is odd.'
    println(num_to_str(1))      // 'one'
    println(num_to_str(2))      // 'two'
    println(num_to_str(352))    // 'many'
}
```

### 枚举

还可以使用`variant`语句将`enum`值（变量）作为分支进行匹配：

```
enum Animal {
    cat
    dog
    goldfish
    pig
}

fn makes_miau(a Animal) bool {
    return match a {
        .cat { true }
        else { false }
    }
}

fn is_land_creature(a Animal) bool {
    return match a {
        .cat { true }
        .dog { true }
        .pig { true }
        else {
            false
        }
    }
}
// OR LIKE THAT
fn is_land_creature_alt(a Animal) bool {
    return match a {
        .goldfish { false }
        else {
            true
        }
    }
}

fn main() {
    my_cat := Animal.cat
    my_goldfish := Animal.goldfish

    println(makes_miau(my_cat))             // true
    println(is_land_creature(my_cat))       // true
    println(is_land_creature(my_goldfish))  // false
}
```

### 练习

1.编写一个V程序，创建一个从1到50的所有偶数数组。 2.编写一个V程序，给定一个数字数组，返回最大值。 3.编写一个V程序来确定颜色（枚举）是红色还是蓝色


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://v-community.gitbook.io/v-by-example/cn/examples/section_2/match.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
