doujing5435 2017-04-14 15:01
浏览 95
已采纳

fmt.Println调用Error而不是String()

I have this code

package main

import (
    "fmt"
    "math"
)

type ErrNegativeSqrt float64

func (s ErrNegativeSqrt) String() string {
    return fmt.Sprintf("%f", float64(s))
}

func (e ErrNegativeSqrt) Error() string {
    return fmt.Sprintf("Cannot Sqrt negative number: %v", float64(e))
}

func Sqrt(x float64) (ErrNegativeSqrt, error) {
    if x < 0 {
        e := ErrNegativeSqrt(x)
        return e, e
    } else {
        return ErrNegativeSqrt(math.Sqrt(x)), nil
    }
}

func main() {
    fmt.Println(Sqrt(2))
    fmt.Println(Sqrt(-2))
}

And the output of this code is

Cannot Sqrt negative number: 1.4142135623730951 <nil> Cannot Sqrt negative number: -2 Cannot Sqrt negative number: -2

When I have implemented the Stringer interface for the ErrNegativeSqrt, why is the fmt.Println invoking the Error() method instead of the String() method?

I am new to go, so I might be missing something very obvious.

  • 写回答

1条回答 默认 最新

  • dongweng9474 2017-04-14 15:06
    关注

    The documentation states how the value is converted to a string:

    1. If an operand implements the error interface, the Error method will be invoked to convert the object to a string, which will then be formatted as required by the verb (if any).

    2. If an operand implements method String() string, that method will be invoked to convert the object to a string, which will then be formatted as required by the verb (if any).

    The error interface comes before Stringer.

    A more idiomatic way to write the function is:

    func Sqrt(x float64) (float64, error) {
      if x < 0 {
        return 0, ErrNegativeSqrt(x)
      }
      return math.Sqrt(x), nil
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 这个电路是如何实现路灯控制器的,原理是什么,怎么求解灯亮起后熄灭的时间如图?
  • ¥15 matlab数字图像处理频率域滤波
  • ¥15 在abaqus做了二维正交切削模型,给刀具添加了超声振动条件后输出切削力为什么比普通切削增大这么多
  • ¥15 ELGamal和paillier计算效率谁快?
  • ¥15 file converter 转换格式失败 报错 Error marking filters as finished,如何解决?
  • ¥15 ubuntu系统下挂载磁盘上执行./提示权限不够
  • ¥15 Arcgis相交分析无法绘制一个或多个图形
  • ¥15 关于#r语言#的问题:差异分析前数据准备,报错Error in data[, sampleName1] : subscript out of bounds请问怎么解决呀以下是全部代码:
  • ¥15 seatunnel-web使用SQL组件时候后台报错,无法找到表格
  • ¥15 fpga自动售货机数码管(相关搜索:数字时钟)