interface-go
path: courses/go-course/interface-go.md
- **fileName**: interface-go
- **Created on**: 2024-08-27 12:28:16
in go you can handle the error as value
package main
import ( "errors" "fmt" )
func main() {
fmt.Println("welcome foo")
value, err := userCalc(10, 0)
if err != nil { fmt.Println(err) }
else {
fmt.Printf("the value for operation func: %f\n", value)
}
return
}
func userCalc(x int, y int) (float64, error) {
if y <= 0 { return 0.0, errors.New("can't divide by 0 or lesss value") }
return float64(x/y) , nil
}
- this how to handle an error in go and there is Error interface build in go
for handle the error
can making an error struct for the error to format the error like what you
want can by this way example:
package main
import ( "fmt")
type UserError struct { name string }
func (e UserError) Error() string { return fmt.Sprintf("Error: %v", e.name) }
func main() {
value, err := userCalc(10, 0)
if err != nil { fmt.Println(err)
}else { fmt.Printf("the value for operation func: %f\n", value)}
return
}
func userCalc(x int, y int) (float64, error) {
if y <= 0 { return 0.0, UserError{name: "division by zero"}}
return float64(x/y) , nil
}
continue:array-slice.md
before:struct-go.md