私は[]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