在Go语言中,类型断言是一种检查接口变量内部具体类型的方法。为了提高代码的可读性,你可以遵循以下几点建议:
func main() {
var i interface{} = "hello"
strValue, ok := i.(string)
if ok {
fmt.Println("The value is a string:", strValue)
} else {
fmt.Println("The value is not a string")
}
}
func main() {
var i interface{} = 42
switch v := i.(type) {
case int:
fmt.Println("It's an int:", v)
case string:
fmt.Println("It's a string:", v)
default:
fmt.Println("Unknown type")
}
}
func main() {
var i interface{} = 42
// Type assertion: expect an int, otherwise handle the error
if intValue, ok := i.(int); ok {
fmt.Println("It's an int:", intValue)
} else {
fmt.Println("The value is not an int")
}
}
type MyInt int
func (m MyInt) String() string {
return fmt.Sprintf("%d", m)
}
func main() {
var i interface{} = MyInt(42)
if strValue, ok := i.(string); ok {
fmt.Println("The value is a string:", strValue)
} else if intValue, ok := i.(MyInt); ok {
fmt.Println("The value is a custom int:", intValue)
} else {
fmt.Println("The value is of unknown type")
}
}
遵循这些建议,可以帮助你编写出更加清晰和易读的Go语言代码。