zoukankan      html  css  js  c++  java
  • Go指南练习_错误

    源地址 https://tour.go-zh.org/methods/20

    一、题目描述

    之前的练习中复制 Sqrt 函数,修改它使其返回 error 值。

    Sqrt 接受到一个负数时,应当返回一个非 nil 的错误值。复数同样也不被支持。

    创建一个新的类型

    type ErrNegativeSqrt float64

    并为其实现

    func (e ErrNegativeSqrt) Error() string

    方法使其拥有 error 值,通过 ErrNegativeSqrt(-2).Error() 调用该方法应返回 "cannot Sqrt negative number: -2"

    *注意:* 在 Error 方法内调用 fmt.Sprint(e) 会让程序陷入死循环。可以通过先转换 e 来避免这个问题:fmt.Sprint(float64(e))。这是为什么呢?

    修改 Sqrt 函数,使其接受一个负数时,返回 ErrNegativeSqrt 值。

     

    二、分析

    • 定义float64的类型ErrNegativeSqrt;
    • 重写Error方法。

    三、Go代码

    package main
    
    import (
        "fmt"
        "math"
    )
    
    type ErrNegativeSqrt float64  //创建一个新的类型
    
    func (e ErrNegativeSqrt) Error() string {
        return fmt.Sprintf("cannot Sqrt negative number:  %v", float64(e))
    }
    
    func Sqrt(x float64) (float64, error) {
        if x < 0 {
            return 0, ErrNegativeSqrt(x)
        }
        return math.Sqrt(x), nil
    }
    
    func main() {
        fmt.Println(Sqrt(2))
        fmt.Println(Sqrt(-2))
    }

    运行结果

  • 相关阅读:
    MySQL "show users"
    MySQL
    A MySQL 'create table' syntax example
    MySQL backup
    MySQL show status
    Tomcat, pathinfo, and servlets
    Servlet forward example
    Servlet redirect example
    Java servlet example
    How to forward from one JSP to another JSP
  • 原文地址:https://www.cnblogs.com/OctoptusLian/p/9209451.html
Copyright © 2011-2022 走看看