在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語言代碼。