Why print slice using fmt.Println (slice) is different in Golang

code A:

package main import "fmt" func main() { slice := IntSlice{0, 1, 2, 3, 4, 5, 6, 7, 8, 9} fmt.Println(slice) } type IntSlice []int 

pin A:

 [0 1 2 3 4 5 6 7 8 9] 

code B:

 package main import "fmt" func main() { slice := IntSlice{0, 1, 2, 3, 4, 5, 6, 7, 8, 9} fmt.Println(slice) } type IntSlice []int func (slice IntSlice) Error() string { return "this is called." } 

pin B:

 this is called. 

why is the behavior of fmt.Println(slice) different for these two codes (A and B)?
or why fmt.Println(slice) automatically calls slice.Error() ?

+5
source share
1 answer

This is documented as part of the fmt behavior (highlighted by me):

Unless they are printed using the verbs% T and% p, special formatting considerations apply for operands that implement certain interfaces. In order of application:

  • If the operand is a reflection. The value, the operand, is replaced by the specific value that it holds, and printing continues from the next rule.

  • If the operand implements the Formatter interface, it will be called. Formatter provides precise formatting control.

  • If the verb% v is used with the flag # (% # v), and the operand implements the GoStringer interface, which will be called.

    If the format (implicitly% v for Println, etc.) is valid for the string (% s% q% v% x% X), the following two rules apply:

  • If the operand implements the error interface, the Error method will be called to convert the object to a string, which will then be formatted at the request of the verb (if any).

  • If the operand implements the string of the String () method, this method will be called to convert the object to a string, which will then be formatted in accordance with the requirements of the verb (if any).

For compound operands, such as slices and structures, the format is applied to the elements of each operand, recursively, and not to the operand as a whole. Thus,% q will indicate each line slice element, and% 6.2f will control the formatting for each element of the floating-point array.

The fmt package sees that slice implements error and prints value.Error() , rather than iterating through the slice and applying formatting to each element.

+7
source

All Articles