Golang中switch case语句如何处理下划线_
Golang中switch case语句如何处理下划线_
package main
import "fmt"
func do(i interface{}) {
switch a := i.(type) {
case int:
fmt.Printf("int")
case string:
fmt.Printf("string")
default:
fmt.Printf("I don't know about type")
}
}
func main() {
do(21)
do("hello")
do(true)
}
上面的代码无法正常工作,因为变量a已声明但未使用。
switch case不允许我使用_。
但我只需要类型信息,不需要那个数据。
有没有其他方法可以实现这个?
谢谢。
更多关于Golang中switch case语句如何处理下划线_的实战教程也可以访问 https://www.itying.com/category-94-b0.html
3 回复
对我来说,直接使用 switch i.(type) { … } 就可以解决问题:
package main
import (
"fmt"
)
func main() {
var i interface{} = "hello"
switch v := i.(type) {
case int:
fmt.Printf("整数:%d\n", v)
case string:
fmt.Printf("字符串:%s\n", v)
default:
fmt.Printf("未知类型:%T\n", v)
}
}
在Go语言中,当使用类型switch时,如果不需要绑定类型断言后的值,可以使用下划线_来忽略它。但下划线不能直接放在类型断言的位置,而是需要在变量声明时使用。
在你的代码中,问题在于a := i.(type)声明了一个变量a,但在case分支中没有使用它。要解决这个问题,可以将a替换为下划线_,表示忽略这个值。
以下是修改后的代码:
package main
import "fmt"
func do(i interface{}) {
switch i.(type) {
case int:
fmt.Printf("int\n")
case string:
fmt.Printf("string\n")
default:
fmt.Printf("I don't know about type\n")
}
}
func main() {
do(21)
do("hello")
do(true)
}
或者,如果你需要在某些case中使用值,但在其他case中不需要,可以混合使用:
package main
import "fmt"
func do(i interface{}) {
switch a := i.(type) {
case int:
fmt.Printf("int: %d\n", a) // 使用a
case string:
fmt.Printf("string: %s\n", a) // 使用a
default:
_ = a // 明确忽略a
fmt.Printf("I don't know about type\n")
}
}
func main() {
do(21)
do("hello")
do(true)
}
在第一个修改中,完全移除了变量绑定,只检查类型。在第二个示例中,在需要时使用变量a,在不需要时用_ = a明确忽略它以避免编译错误。

