b/w 스위치와 일치하는 용도와 차이

모든 사람은 반드시 선택문구를 사용하여 pattern matching 또는 상등성 검사를 해야 한다.Rust, F#, Kotlin, Scala, V, Python, (future)match, switch, C, C++, Go, C# 등은 switch을 사용한다.
같은 목적을 위해 다른 이름을 써야 하나요?본고는 이 둘 사이의 차이와 용법을 천명하려고 한다.
switch 주장case 문장은 값 목록에 따라 변수가 같은지 여부를 테스트할 수 있습니다.모든 값은 break이라고 불리지만 switch으로 종료해야 한다.default에는 열거되지 않은 다른 사례를 처리하는 switch사례도 있다.
다음은 간단한 i C++ 문 프로그램입니다.
#include <iostream>

int main()
{
  int i = 0;
  switch (i)
    {
    case 0:
      std::cout << "i is zero";
      break;

    case 1:
      std::cout << "i is one";
      break;

    default:
      std::cout << "invalid";
      break;
    }
}
이 프로그램은 변수 intswitch10i 문장 검사 i == 0의 값으로 성명한다.첫 번째 사례는 i is zero 조건 충족 시 평가되므로 switch이 인쇄됩니다.
비록 switch은 어느 정도 한계가 있다.
  • int은 정수 값인 char, enumswitch에만 적용
  • switch은 검사 등식
  • 에만 사용 가능
  • match은 표현식
  • 으로 사용할 수 없습니다.
    match 문구/표현식switch은 문장으로도 사용할 수 있고 표현식으로도 사용할 수 있다. default과 매우 비슷하다. 단지 상기 제한을 해결하고 전환을 통해 no case이나 case과 같은 추가 키워드를 저장했다. (예를 들어 Python은 default이 있지만 이것은 문장이다).else_ 또는 match으로 교체됩니다(기본값만 사용할 수도 있습니다).1..2[1, 2)과 같은 범위, 즉 1..=31...3 사이의 범위, 또는 [1, 3], 즉 2 | 3 | 4, 3, 4, 5 또는 var 사이의 범위를 지원하는데 그 중 하나가 진짜라면 object/match과 일치한다.
    다음 Learn Rust by Examples의 예는 Rust로 작성되었습니다.
    Go 에서 발췌

    간단한 예
    fn main() {
        let x = 1;
    
        match x {
            1 => println!("one"),
            2 => println!("two"),
            3 => println!("three"),
            4 => println!("four"),
            5 => println!("five"),
           // else clause, executed when none of value matches
            _ => println!("something else"),
        }
    }
    

    범위를 사용하고 여러 개의 값과 표현식을 조합합니다
    fn main() {
        let x = 1;
        let message = match x {
            0 | 1 => "not many",  // check if matches either to 0 or 1
            2..=9 => "a few",     // check if its in a range of `[2, 9]`
            10..15 => "too many", // check if its in a range of `[10, 15)`
            // else clause, if neither of the cases matches then "lots of
            // many" will be assigned
            _ => "lots of many",
        };
    
        assert_eq!(message, "a few");
    }
    

    예외적 상황
    일부 언어, 예를 들어 JS, TS, default 등은 switch 문구가 있지만 모든 기본 데이터 유형을 지원한다. 비록 지원 범위가 아니더라도 이를 표현식으로 사용하고 break을 키워드, 패턴 일치 등으로 사용한다.
    Go에서는 모든 상황에서 interface{}을 사용할 필요가 없습니다. 자동으로 실행되며, switch을 사용하여 변수의 유형을 측정할 수 있습니다.
    Go의 Go By Examples
    match 에서 발췌

    간단한 예
    package main
    
    import (
        "fmt"
        "time"
    )
    
    func main() {
    
        // Here's a basic `switch`.
        i := 2
        fmt.Print("Write ", i, " as ")
        switch i {
        case 1:
            fmt.Println("one")
        case 2:
            fmt.Println("two")
        case 3:
            fmt.Println("three")
        }
    
        // You can use commas to separate multiple expressions
        // in the same `case` statement. We use the optional
        // `default` case in this example as well.
        switch time.Now().Weekday() {
        case time.Saturday, time.Sunday:
            fmt.Println("It's the weekend")
        default:
            fmt.Println("It's a weekday")
        }
    
        // `switch` without an expression is an alternate way
        // to express if/else logic. Here we also show how the
        // `case` expressions can be non-constants.
        t := time.Now()
        switch {
        case t.Hour() < 12:
            fmt.Println("It's before noon")
        default:
            fmt.Println("It's after noon")
        }
    
        // A type `switch` compares types instead of values.  You
        // can use this to discover the type of an interface
        // value.  In this example, the variable `t` will have the
        // type corresponding to its clause.
        whatAmI := func(i interface{}) {
            switch t := i.(type) {
            case bool:
                fmt.Println("I'm a bool")
            case int:
                fmt.Println("I'm an int")
            default:
                fmt.Printf("Don't know type %T\n", t)
            }
        }
        whatAmI(true)
        whatAmI(1)
        whatAmI("hey")
    }
    

    결론switchif-else은 긴 match 문장을 작성하는 편리한 방법으로 가독성을 높이고 코드를 더욱 건장하게 하는 데 사용된다.
    일반적으로 switchpattern matching에 사용되고 문장과 표현식일 수도 있으며 switch은 등식 검사에 사용되며 문장에 불과하다.
    일부 언어는 심지어 when(f.e. Kotlin과 match start...end과 같은 의미를 가진다)을 사용하지 않을 수도 있다.
    동적 유형 언어와 정적 유형 언어는 특정한 용례에서 보통 다른 일을 한다.어떤 사람들은 언어가 너무 복잡해지지 않도록 어떤 기능을 제공하거나 허락하지 않을 수도 있다.
    마찬가지로 V는 복잡성을 없애기 위해 마지막 요소인 [start, end]만 지원합니다.
    몇몇 언어는 간단하고 사용하기 쉽도록 switch을 보존할 수도 있다.

    도구책
  • Match in Rust
  • Match in V
  • Match in Python
  • Match in F#
  • Match in Scala
  • Switch in Go
  • Match in Kotlin
  • Switch in C#
  • Pattern Matching
  • 만약 이 문장에 무슨 착오가 있으면 평론에 회답해 주십시오.

    좋은 웹페이지 즐겨찾기