b/w 스위치와 일치하는 용도와 차이
16442 단어 gorustcppcomputerscience
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;
}
}
이 프로그램은 변수 int
을 switch
10i
문장 검사 i == 0
의 값으로 성명한다.첫 번째 사례는 i is zero
조건 충족 시 평가되므로 switch
이 인쇄됩니다.비록
switch
은 어느 정도 한계가 있다.int
은 정수 값인 char
, enum
및 switch
에만 적용switch
은 검사 등식 match
은 표현식 match
문구/표현식switch
은 문장으로도 사용할 수 있고 표현식으로도 사용할 수 있다. default
과 매우 비슷하다. 단지 상기 제한을 해결하고 전환을 통해 no case
이나 case
과 같은 추가 키워드를 저장했다. (예를 들어 Python은 default
이 있지만 이것은 문장이다).else
은 _
또는 match
으로 교체됩니다(기본값만 사용할 수도 있습니다).1..2
은 [1, 2)
과 같은 범위, 즉 1..=3
과 1...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")
}
결론
switch
과 if-else
은 긴 match
문장을 작성하는 편리한 방법으로 가독성을 높이고 코드를 더욱 건장하게 하는 데 사용된다.일반적으로
switch
은 pattern matching에 사용되고 문장과 표현식일 수도 있으며 switch
은 등식 검사에 사용되며 문장에 불과하다.일부 언어는 심지어
when
(f.e. Kotlin과 match
이 start...end
과 같은 의미를 가진다)을 사용하지 않을 수도 있다.동적 유형 언어와 정적 유형 언어는 특정한 용례에서 보통 다른 일을 한다.어떤 사람들은 언어가 너무 복잡해지지 않도록 어떤 기능을 제공하거나 허락하지 않을 수도 있다.
마찬가지로 V는 복잡성을 없애기 위해 마지막 요소인
[start, end]
만 지원합니다.몇몇 언어는 간단하고 사용하기 쉽도록
switch
을 보존할 수도 있다.도구책
Reference
이 문제에 관하여(b/w 스위치와 일치하는 용도와 차이), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://dev.to/delta456/use-of-switch-and-match-3h7g텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)