있습니다. []interface{}
입니다. 반복하고, 스위치 내의 각 요소 유형을 확인하고 있습니다. 여러 개의 숫자 유형 (예 : int || float32 || float64
)에 '포괄적 인'사례를 추가하고 싶습니다.Golang에서 switch 내에서 유형에 대한 논리 OR을 구현하십시오.
요소가 하나의 고유 한 유형인지 여부를 확인할 수 있지만 여러 유형을 검사하기위한 구문을 ||
(또는)으로 확인할 수없는 것 같습니다.
이것이 가능합니까? 나는 (Playground) 시도했다 :
package main
import (
"fmt"
)
func main() {
things := []interface{}{"foo", 12, 4.5, true}
for _, thing := range things {
switch t := thing.(type) {
// How can we implement logical OR for types to implement a catch-all for numerics?
// Throws error: "type <type> is not an expression"
// case (int || float64) :
// fmt.Printf("Thing %v is a 'numeric' type: %T\n", thing, t)
// Single discrete types work fine, of course
case string :
fmt.Printf("Thing %v is of type: %T\n", thing, t)
case int :
fmt.Printf("Thing %v is of type: %T\n", thing, t)
case float64 :
fmt.Printf("Thing %v is of type: %T\n", thing, t)
case bool :
fmt.Printf("Thing %v is of type: %T\n", thing, t)
default :
fmt.Printf("Thing %v is of unknown type\n", thing)
}
}
}
다운 유권자, 이유를 설명해 주시겠습니까? (여기서 싸우는 것이 아니라, 더 나은 포럼 멤버가되어이 명백한 실수로부터 배우는 것이 진정 진실이다. – gpanda
내가 누가 다운 투표를했는지 말할 수는 없지만, 스펙을 읽거나 [A Tour of Go] (https://tour.golang.org/welcome/1)를 읽으면 쉽게 대답 할 수있는 질문에 자주 사용됩니다. "연구 노력이 부족하다"는 단점이있다. – Flimzy