go语言Exercise: Errors
2012-05-09 15:41
381 查看
Copy your
Create a new type
and make it an
method such that
Note: a call to
will send the program into an infinite loop. You can avoid this by converting
Why?
Change your
when given a negative number.
package main
import (
"fmt"
)
type ErrNegativeSqrt float64
func (e ErrNegativeSqrt) Error() string{
return fmt.Sprintf("cantnot Sqrt negative number: %v", float64(e))
}
func Sqrt(f float64) (float64, error) {
if f < 0 {
return 0, ErrNegativeSqrt(f)
}
z := f
for i := 0; i < 10; i++ {
z = (z + f/z)/2
}
return z, nil
}
func main() {
if value, err := Sqrt(-2); err != nil {
fmt.Println(err)
} else {
fmt.Println(value)
}
if value, err := Sqrt(2); err != nil {
fmt.Println(err)
} else {
fmt.Println(value)
}
}
Sqrtfunction from the earlier exercises and modify it to return an
errorvalue.
Sqrtshould return a non-nil error value when given a negative number, as it doesn't support complex numbers.
Create a new type
type ErrNegativeSqrt float64
and make it an
errorby giving it a
func (e ErrNegativeSqrt) Error() string
method such that
ErrNegativeSqrt(-2).Error()returns
"cannot Sqrt negative number: -2".
Note: a call to
fmt.Print(e)inside the
Errormethod
will send the program into an infinite loop. You can avoid this by converting
efirst:
fmt.Print(float64(e)).
Why?
Change your
Sqrtfunction to return an
ErrNegativeSqrtvalue
when given a negative number.
package main
import (
"fmt"
)
type ErrNegativeSqrt float64
func (e ErrNegativeSqrt) Error() string{
return fmt.Sprintf("cantnot Sqrt negative number: %v", float64(e))
}
func Sqrt(f float64) (float64, error) {
if f < 0 {
return 0, ErrNegativeSqrt(f)
}
z := f
for i := 0; i < 10; i++ {
z = (z + f/z)/2
}
return z, nil
}
func main() {
if value, err := Sqrt(-2); err != nil {
fmt.Println(err)
} else {
fmt.Println(value)
}
if value, err := Sqrt(2); err != nil {
fmt.Println(err)
} else {
fmt.Println(value)
}
}
相关文章推荐
- Go语言学习之errors包(The way to go)
- go语言Exercise: Maps
- go语言Exercise: Slices
- go语言Exercise: Fibonacci closure
- go语言Advanced Exercise: Complex cube roots
- go语言Exercise: Images
- go语言Exercise: Rot13 Reader
- Go 语言实现exercise--Loops and Functions
- go语言Exercise: Equivalent Binary Trees
- 在 Go 语言中处理 Unicode
- go语言特性113
- GO语言UDP小笔记
- Go语言学习札记—— 第二章 Go编程环境(1)
- GO语言时间格式化,奇葩得不想说了
- [2]Go语言特性概览
- notepad++支持go语言高亮与go语言插件
- (转载)Go语言开发环境配置
- Go语言并发与并行学习笔记(三)
- go语言学习优秀博文、论坛收藏<持续更新>
- Go语言之并发示例-Pool(二)