
#環境
golang1.8.3
gogland
#質問
go
1package main 2import ( 3 "fmt" 4 "regexp" 5) 6 7func main() { 8 messageType := []string{"check", "on", "off"} //スライス作成 9 10 re1 := regexp.MustCompile(messageType[0]) //checkをコンパイル 11 re2 := regexp.MustCompile(messageType[1]) //onをコンパイル 12 re3 := regexp.MustCompile(messageType[2]) //offをコンパイル 13 14 message := "on and off" //on, offの2つが入っている文字列 15 16 switch { 17 case re1.MatchString(message): //messageにcheckが含まれていた場合 18 fmt.Print("check") 19 20 case re2.MatchString(message): //messageにonが含まれていた場合 21 fmt.Print("on") 22 23 case re3.MatchString(message): //messageにoffが含まれていた場合 24 fmt.Print("off") 25 26 default: //その他の時 27 fmt.Print("I cant understand what you mean") 28 } 29}
このコードは、スライスの中身が変数messageに入っていたらcaseの中を処理するコードなのですが、messageの中に、2つ入っている場合、おそらくcaseで上に来ているonの中が処理された後にswitch構文から抜けると思います。
上記のように、caseの複数が該当する時に、二つの処理をさせるためにはどうすればいいですか?
#####関連した別件
上記のコードで、
go
1re1 := regexp.MustCompile(messageType[0]) //checkをコンパイル 2re2 := regexp.MustCompile(messageType[1]) //onをコンパイル 3re3 := regexp.MustCompile(messageType[2]) //offをコンパイル
となっている部分なんですが、forを使って簡潔に書く方法があれば教えていただきたいです。
例えば以下のようにすると変数reが上書きされてしまうと思います。。
変数名にiを関連付ければなんとかなる気もしますが、スマートな方法があればと思います。。
go
1i := 0 2for _, i range messageType{ 3 re := regexp.MustCompile(messageType[i]) 4 if i == 3{ break } 5 i++ 6}

回答4件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
退会済みユーザー
2017/08/18 05:01
退会済みユーザー
2017/08/18 20:05
2017/08/19 02:05