Home >Backend Development >Golang >Why Does `fmt.Println` Prioritize `Error()` over `String()` in Go?

Why Does `fmt.Println` Prioritize `Error()` over `String()` in Go?

DDD
DDDOriginal
2024-11-20 20:09:16606browse

Why Does `fmt.Println` Prioritize `Error()` over `String()` in Go?

Precedence of Error() over String() in fmt.Println

In Go, when printing objects using fmt.Println, the String() method is typically used to convert the object to a string for printing. However, in certain cases, the Error() method takes precedence over String().

This behavior is defined by the implementation of fmt.Println. The package documentation states that if an object implements the error interface, the Error() method will be invoked to convert the object to a string. This string is then formatted as required by the verb (if any).

The implementation of Error() is given higher priority than String() because errors are considered more important in practice. This ensures that any errors are clearly displayed, even if a custom String() method is defined.

To illustrate this concept, consider the following example:

package main

import "fmt"

type Person struct {
    Name string
    Age  int
}

func (p *Person) String() string {
    return fmt.Sprintf("%v (%v years)", p.Name, p.Age)
}

func (p *Person) Error() string {
    return fmt.Sprintf("Failed")
}

func main() {
    a := &Person{"Arthur Dent", 42}
    z := &Person{"Zaphod Beeblebrox", 9001}
    fmt.Println(a, z)
}

In this example, both Person types implement the String() and Error() methods. However, when the objects are printed using fmt.Println, the Error() method is invoked instead of String(), resulting in the following output:

Failed Failed

This is because Error() has higher precedence than String() in fmt.Println, ensuring that any errors are clearly displayed.

Therefore, when working with objects that implement both Error() and String(), it is important to consider the desired output and adjust the implementation accordingly.

The above is the detailed content of Why Does `fmt.Println` Prioritize `Error()` over `String()` in Go?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn