fmt

package
v1.21.3 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 14, 2023 License: MIT Imports: 1 Imported by: 0

Documentation

Overview

Package fmt implements formatted I/O with functions analogous to C's printf and scanf. The format 'verbs' are derived from C's but are simpler.

Printing

The verbs:

General:

%v	the value in a default format
	when printing structs, the plus flag (%+v) adds field names
%#v	a Go-syntax representation of the value
%T	a Go-syntax representation of the type of the value
%%	a literal percent sign; consumes no value

Boolean:

%t	the word true or false

Integer:

%b	base 2
%c	the character represented by the corresponding Unicode code point
%d	base 10
%o	base 8
%O	base 8 with 0o prefix
%q	a single-quoted character literal safely escaped with Go syntax.
%x	base 16, with lower-case letters for a-f
%X	base 16, with upper-case letters for A-F
%U	Unicode format: U+1234; same as "U+%04X"

Floating-point and complex constituents:

%b	decimalless scientific notation with exponent a power of two,
	in the manner of strconv.FormatFloat with the 'b' format,
	e.g. -123456p-78
%e	scientific notation, e.g. -1.234456e+78
%E	scientific notation, e.g. -1.234456E+78
%f	decimal point but no exponent, e.g. 123.456
%F	synonym for %f
%g	%e for large exponents, %f otherwise. Precision is discussed below.
%G	%E for large exponents, %F otherwise
%x	hexadecimal notation (with decimal power of two exponent), e.g. -0x1.23abcp+20
%X	upper-case hexadecimal notation, e.g. -0X1.23ABCP+20

String and slice of bytes (treated equivalently with these verbs):

%s	the uninterpreted bytes of the string or slice
%q	a double-quoted string safely escaped with Go syntax
%x	base 16, lower-case, two characters per byte
%X	base 16, upper-case, two characters per byte

Slice:

%p	address of 0th element in base 16 notation, with leading 0x

Pointer:

%p	base 16 notation, with leading 0x
The %b, %d, %o, %x and %X verbs also work with pointers,
formatting the value exactly as if it were an integer.

The default format for %v is:

bool:                    %t
int, int8 etc.:          %d
uint, uint8 etc.:        %d, %#x if printed with %#v
float32, complex64, etc: %g
string:                  %s
chan:                    %p
pointer:                 %p

For compound objects, the elements are printed using these rules, recursively, laid out like this:

struct:             {field0 field1 ...}
array, slice:       [elem0 elem1 ...]
maps:               map[key1:value1 key2:value2 ...]
pointer to above:   &{}, &[], &map[]

Width is specified by an optional decimal number immediately preceding the verb. If absent, the width is whatever is necessary to represent the value. Precision is specified after the (optional) width by a period followed by a decimal number. If no period is present, a default precision is used. A period with no following number specifies a precision of zero. Examples:

%f     default width, default precision
%9f    width 9, default precision
%.2f   default width, precision 2
%9.2f  width 9, precision 2
%9.f   width 9, precision 0

Width and precision are measured in units of Unicode code points, that is, runes. (This differs from C's printf where the units are always measured in bytes.) Either or both of the flags may be replaced with the character '*', causing their values to be obtained from the next operand (preceding the one to format), which must be of type int.

For most values, width is the minimum number of runes to output, padding the formatted form with spaces if necessary.

For strings, byte slices and byte arrays, however, precision limits the length of the input to be formatted (not the size of the output), truncating if necessary. Normally it is measured in runes, but for these types when formatted with the %x or %X format it is measured in bytes.

For floating-point values, width sets the minimum width of the field and precision sets the number of places after the decimal, if appropriate, except that for %g/%G precision sets the maximum number of significant digits (trailing zeros are removed). For example, given 12.345 the format %6.3f prints 12.345 while %.3g prints 12.3. The default precision for %e, %f and %#g is 6; for %g it is the smallest number of digits necessary to identify the value uniquely.

For complex numbers, the width and precision apply to the two components independently and the result is parenthesized, so %f applied to 1.2+3.4i produces (1.200000+3.400000i).

When formatting a single integer code point or a rune string (type []rune) with %q, invalid Unicode code points are changed to the Unicode replacement character, U+FFFD, as in strconv.QuoteRune.

Other flags:

'+'	always print a sign for numeric values;
	guarantee ASCII-only output for %q (%+q)
'-'	pad with spaces on the right rather than the left (left-justify the field)
'#'	alternate format: add leading 0b for binary (%#b), 0 for octal (%#o),
	0x or 0X for hex (%#x or %#X); suppress 0x for %p (%#p);
	for %q, print a raw (backquoted) string if strconv.CanBackquote
	returns true;
	always print a decimal point for %e, %E, %f, %F, %g and %G;
	do not remove trailing zeros for %g and %G;
	write e.g. U+0078 'x' if the character is printable for %U (%#U).
' '	(space) leave a space for elided sign in numbers (% d);
	put spaces between bytes printing strings or slices in hex (% x, % X)
'0'	pad with leading zeros rather than spaces;
	for numbers, this moves the padding after the sign;
	ignored for strings, byte slices and byte arrays

Flags are ignored by verbs that do not expect them. For example there is no alternate decimal format, so %#d and %d behave identically.

For each Printf-like function, there is also a Print function that takes no format and is equivalent to saying %v for every operand. Another variant Println inserts blanks between operands and appends a newline.

Regardless of the verb, if an operand is an interface value, the internal concrete value is used, not the interface itself. Thus:

var i interface{} = 23
fmt.Printf("%v\n", i)

will print 23.

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

1. If the operand is a reflect.Value, the operand is replaced by the concrete value that it holds, and printing continues with the next rule.

2. If an operand implements the Formatter interface, it will be invoked. In this case the interpretation of verbs and flags is controlled by that implementation.

3. If the %v verb is used with the # flag (%#v) and the operand implements the GoStringer interface, that will be invoked.

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

4. 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).

5. 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).

For compound operands such as slices and structs, the format applies to the elements of each operand, recursively, not to the operand as a whole. Thus %q will quote each element of a slice of strings, and %6.2f will control formatting for each element of a floating-point array.

However, when printing a byte slice with a string-like verb (%s %q %x %X), it is treated identically to a string, as a single item.

To avoid recursion in cases such as

type X string
func (x X) String() string { return Sprintf("<%s>", x) }

convert the value before recurring:

func (x X) String() string { return Sprintf("<%s>", string(x)) }

Infinite recursion can also be triggered by self-referential data structures, such as a slice that contains itself as an element, if that type has a String method. Such pathologies are rare, however, and the package does not protect against them.

When printing a struct, fmt cannot and therefore does not invoke formatting methods such as Error or String on unexported fields.

Explicit argument indexes

In Printf, Sprintf, and Fprintf, the default behavior is for each formatting verb to format successive arguments passed in the call. However, the notation [n] immediately before the verb indicates that the nth one-indexed argument is to be formatted instead. The same notation before a '*' for a width or precision selects the argument index holding the value. After processing a bracketed expression [n], subsequent verbs will use arguments n+1, n+2, etc. unless otherwise directed.

For example,

fmt.Sprintf("%[2]d %[1]d\n", 11, 22)

will yield "22 11", while

fmt.Sprintf("%[3]*.[2]*[1]f", 12.0, 2, 6)

equivalent to

fmt.Sprintf("%6.2f", 12.0)

will yield " 12.00". Because an explicit index affects subsequent verbs, this notation can be used to print the same values multiple times by resetting the index for the first argument to be repeated:

fmt.Sprintf("%d %d %#[1]x %#x", 16, 17)

will yield "16 17 0x10 0x11".

Format errors

If an invalid argument is given for a verb, such as providing a string to %d, the generated string will contain a description of the problem, as in these examples:

Wrong type or unknown verb: %!verb(type=value)
	Printf("%d", "hi"):        %!d(string=hi)
Too many arguments: %!(EXTRA type=value)
	Printf("hi", "guys"):      hi%!(EXTRA string=guys)
Too few arguments: %!verb(MISSING)
	Printf("hi%d"):            hi%!d(MISSING)
Non-int for width or precision: %!(BADWIDTH) or %!(BADPREC)
	Printf("%*s", 4.5, "hi"):  %!(BADWIDTH)hi
	Printf("%.*s", 4.5, "hi"): %!(BADPREC)hi
Invalid or invalid use of argument index: %!(BADINDEX)
	Printf("%*[2]d", 7):       %!d(BADINDEX)
	Printf("%.[2]d", 7):       %!d(BADINDEX)

All errors begin with the string "%!" followed sometimes by a single character (the verb) and end with a parenthesized description.

If an Error or String method triggers a panic when called by a print routine, the fmt package reformats the error message from the panic, decorating it with an indication that it came through the fmt package. For example, if a String method calls panic("bad"), the resulting formatted message will look like

%!s(PANIC=bad)

The %!s just shows the print verb in use when the failure occurred. If the panic is caused by a nil receiver to an Error or String method, however, the output is the undecorated string, "<nil>".

Scanning

An analogous set of functions scans formatted text to yield values. Scan, Scanf and Scanln read from os.Stdin; Fscan, Fscanf and Fscanln read from a specified io.Reader; Sscan, Sscanf and Sscanln read from an argument string.

Scan, Fscan, Sscan treat newlines in the input as spaces.

Scanln, Fscanln and Sscanln stop scanning at a newline and require that the items be followed by a newline or EOF.

Scanf, Fscanf, and Sscanf parse the arguments according to a format string, analogous to that of Printf. In the text that follows, 'space' means any Unicode whitespace character except newline.

In the format string, a verb introduced by the % character consumes and parses input; these verbs are described in more detail below. A character other than %, space, or newline in the format consumes exactly that input character, which must be present. A newline with zero or more spaces before it in the format string consumes zero or more spaces in the input followed by a single newline or the end of the input. A space following a newline in the format string consumes zero or more spaces in the input. Otherwise, any run of one or more spaces in the format string consumes as many spaces as possible in the input. Unless the run of spaces in the format string appears adjacent to a newline, the run must consume at least one space from the input or find the end of the input.

The handling of spaces and newlines differs from that of C's scanf family: in C, newlines are treated as any other space, and it is never an error when a run of spaces in the format string finds no spaces to consume in the input.

The verbs behave analogously to those of Printf. For example, %x will scan an integer as a hexadecimal number, and %v will scan the default representation format for the value. The Printf verbs %p and %T and the flags # and + are not implemented. For floating-point and complex values, all valid formatting verbs (%b %e %E %f %F %g %G %x %X and %v) are equivalent and accept both decimal and hexadecimal notation (for example: "2.3e+7", "0x4.5p-8") and digit-separating underscores (for example: "3.14159_26535_89793").

Input processed by verbs is implicitly space-delimited: the implementation of every verb except %c starts by discarding leading spaces from the remaining input, and the %s verb (and %v reading into a string) stops consuming input at the first space or newline character.

The familiar base-setting prefixes 0b (binary), 0o and 0 (octal), and 0x (hexadecimal) are accepted when scanning integers without a format or with the %v verb, as are digit-separating underscores.

Width is interpreted in the input text but there is no syntax for scanning with a precision (no %5.2f, just %5f). If width is provided, it applies after leading spaces are trimmed and specifies the maximum number of runes to read to satisfy the verb. For example,

Sscanf(" 1234567 ", "%5s%d", &s, &i)

will set s to "12345" and i to 67 while

Sscanf(" 12 34 567 ", "%5s%d", &s, &i)

will set s to "12" and i to 34.

In all the scanning functions, a carriage return followed immediately by a newline is treated as a plain newline (\r\n means the same as \n).

In all the scanning functions, if an operand implements method Scan (that is, it implements the Scanner interface) that method will be used to scan the text for that operand. Also, if the number of arguments scanned is less than the number of arguments provided, an error is returned.

All arguments to be scanned must be either pointers to basic types or implementations of the Scanner interface.

Like Scanf and Fscanf, Sscanf need not consume its entire input. There is no way to recover how much of the input string Sscanf used.

Note: Fscan etc. can read one character (rune) past the input they return, which means that a loop calling a scan routine may skip some of the input. This is usually a problem only when there is no space between input values. If the reader provided to Fscan implements ReadRune, that method will be used to read characters. If the reader also implements UnreadRune, that method will be used to save the character and successive calls will not lose data. To attach ReadRune and UnreadRune methods to a reader without that capability, use bufio.NewReader.

Example (Formats)

これらの例は、フォーマット文字列を使用して印刷する基本的な方法を示しています。Printf、Sprintf、およびFprintfは、次の引数の書式を指定するフォーマット文字列を受け取ります。たとえば、%d(これを「動詞」と呼びます)は、対応する引数を10進数で表示することを意味します。その引数は整数(または整数を含むもの、例えば整数のスライス)でなければなりません。動詞%v('v'は'value'を意味します)は、引数をそのデフォルトの形式で表示します。PrintまたはPrintlnのように。特別な動詞%T('T'は'Type'を意味します)は、値ではなく引数の型を表示します。これらの例は網羅的ではありません。詳細については、パッケージのコメントを参照してください。

package main

import (
	"github.com/shogo82148/std/fmt"
	"github.com/shogo82148/std/math"
	"github.com/shogo82148/std/time"
)

func main() {

	// %vはデフォルトの形式であることを示す基本的な例のセットです。この場合、整数に対しては10進数の形式(%d)が明示的に要求されることがあります。出力はPrintlnが生成するものと同じです。
	integer := 23
	// それぞれの出力は「23」です(引用符なし)。
	fmt.Println(integer)
	fmt.Printf("%v\n", integer)
	fmt.Printf("%d\n", integer)

	// 特別な動詞%Tは、値ではなくアイテムの型を示します。
	fmt.Printf("%T %T\n", integer, &integer)
	// 結果: int *int

	// Println(x) は Printf("%v\n", x) と同じなので、以下の例ではPrintfのみを使用します。
	// 各例は、整数や文字列など特定の型の値をどのようにフォーマットするかを示しています。
	// 各フォーマット文字列は %v で始めてデフォルトの出力を示し、それに続けて1つ以上のカスタムフォーマットが続きます。

	// ブール値は、%v や %t とともに "true" または "false" として表示されます。
	truth := true
	fmt.Printf("%v %t\n", truth, truth)
	// 結果: true true

	// 整数は %v や %d を使って10進数で表示されます。
	// %x を使うと16進数で表示され、%o を使うと8進数、%b を使うと2進数で表示されます。
	answer := 42
	fmt.Printf("%v %d %x %o %b\n", answer, answer, answer, answer, answer)
	// 結果: 42 42 2a 52 101010

	// 浮動小数点数は複数のフォーマットを持っています: %v と %g はコンパクトな表現を出力し、
	// %f は小数点を出力し、%e は指数表記を使用します。ここで使用されている %6.2f のフォーマットは、
	// 浮動小数点値の表示方法を制御するために幅と精度を設定する方法を示しています。この場合、6 は
	// 値の出力テキストの総幅です(出力の余分なスペースに注意してください)。2 は表示する小数点以下の桁数です。
	pi := math.Pi
	fmt.Printf("%v %g %.2f (%6.2f) %e\n", pi, pi, pi, pi, pi)
	// 結果:3.141592653589793 3.141592653589793 3.14 (  3.14) 3.141593e+00

	// 複素数は、実部と虚部の浮動小数点を括弧で囲んで、虚部の後に「i」を付けた形式です。
	point := 110.7 + 22.5i
	fmt.Printf("%v %g %.2f %.2e\n", point, point, point, point)
	// 結果: (110.7+22.5i) (110.7+22.5i) (110.70+22.50i) (1.11e+02+2.25e+01i)

	// Runesは整数ですが、%cで印刷するとそのUnicode値に対応する文字が表示されます。
	// %qの動詞はクオートされた文字として表示し、%Uは16進数のUnicodeコードポイントとして表示し、
	// %#Uはコードポイントとクオートされた表示可能な形式の両方として表示します。
	smile := '😀'
	fmt.Printf("%v %d %c %q %U %#U\n", smile, smile, smile, smile, smile, smile)
	// 結果: 128512 128512 😀 '😀' U+1F600 U+1F600 '😀'

	// 文字列は、%vと%sはそのまま、%qは引用符付き文字列、そして%#qはバッククォート付き文字列としてフォーマットされます。
	placeholders := `foo "bar"`
	fmt.Printf("%v %s %q %#q\n", placeholders, placeholders, placeholders, placeholders)
	// 結果:foo "bar" foo "bar" "foo \"bar\"" `foo "bar"`

	// %vでフォーマットされたマップは、キーと値をデフォルトの形式で表示します。
	// %#v形式(#はこのコンテキストで「フラグ」と呼ばれます)では、マップをGoのソース形式で表示します。
	// マップはキーの値に応じて一貫した順序で表示されます。
	isLegume := map[string]bool{
		"peanut":    true,
		"dachshund": false,
	}
	fmt.Printf("%v %#v\n", isLegume, isLegume)
	// 結果: map[dachshund:false peanut:true] map[string]bool{"dachshund":false, "peanut":true}

	// %vでフォーマットされた構造体は、そのデフォルトの形式でフィールドの値を表示します。
	// %+vの形式はフィールドを名前付きで表示しますが、%#vは構造体をGoのソース形式でフォーマットします。
	person := struct {
		Name string
		Age  int
	}{"Kim", 22}
	fmt.Printf("%v %+v %#v\n", person, person, person)
	// 結果: {Kim 22} {Name:Kim Age:22} struct { Name string; Age int }{Name:"Kim", Age:22}

	// ポインタのデフォルトのフォーマットは、アンパサンドに続く元の値を表示します。
	// %p フォーマット指定子はポインタの値を16進数で表示します。ここでは、
	// %p への引数には型付きの nil を使用しています。なぜなら、非 nil のポインタ
	// の値は実行ごとに変化するためです;コメントアウトされた Printf 呼び出し
	// を自分で実行するとわかります。
	pointer := &person
	fmt.Printf("%v %p\n", pointer, (*int)(nil))

	// 結果: &{Kim 22} 0x0
	// fmt.Printf("%v %p\n", pointer, pointer)
	// 結果: &{Kim 22} 0x010203 // 上のコメントを参照してください。

	// 配列やスライスは、各要素に対してフォーマットを適用して表示されます。
	greats := [5]string{"Kitano", "Kobayashi", "Kurosawa", "Miyazaki", "Ozu"}
	fmt.Printf("%v %q\n", greats, greats)
	// 結果: [北野 小林 黒沢 宮崎 小津] ["北野" "小林" "黒沢" "宮崎" "小津"]

	kGreats := greats[:3]
	fmt.Printf("%v %q %#v\n", kGreats, kGreats, kGreats)
	// 結果: [北野 小林 黒沢] ["北野" "小林" "黒沢"] []string{"北野", "小林", "黒沢"}

	// バイトスライスは特別です。%dのような整数の形式で要素を印字します。%sと%qの形式ではスライスを文字列として扱います。%xの動詞は、スペースフラグを持つ特別な形式で、バイト間にスペースを挿入します。
	cmd := []byte("a⌘")
	fmt.Printf("%v %d %s %q %x % x\n", cmd, cmd, cmd, cmd, cmd, cmd)
	// 結果: [97 226 140 152] [97 226 140 152] a⌘ "a⌘" 61e28c98 61 e2 8c 98

	// Stringerを実装するタイプは文字列と同じように表示されます。Stringerは文字列を返すため、%qなどの文字列専用のフォーマット指定子を使用して印刷することができます。
	now := time.Unix(123456789, 0).UTC()
	fmt.Printf("%v %q\n", now, now)
	// 結果: 1973年11月29日 21時33分09秒 +0000 UTC "1973年11月29日 21時33分09秒 +0000 UTC"

}
Output:
23
23
23
int *int
true true
42 42 2a 52 101010
3.141592653589793 3.141592653589793 3.14 (  3.14) 3.141593e+00
(110.7+22.5i) (110.7+22.5i) (110.70+22.50i) (1.11e+02+2.25e+01i)
128512 128512 😀 '😀' U+1F600 U+1F600 '😀'
foo "bar" foo "bar" "foo \"bar\"" `foo "bar"`
map[dachshund:false peanut:true] map[string]bool{"dachshund":false, "peanut":true}
{Kim 22} {Name:Kim Age:22} struct { Name string; Age int }{Name:"Kim", Age:22}
&{Kim 22} 0x0
[Kitano Kobayashi Kurosawa Miyazaki Ozu] ["Kitano" "Kobayashi" "Kurosawa" "Miyazaki" "Ozu"]
[Kitano Kobayashi Kurosawa] ["Kitano" "Kobayashi" "Kurosawa"] []string{"Kitano", "Kobayashi", "Kurosawa"}
[97 226 140 152] [97 226 140 152] a⌘ "a⌘" 61e28c98 61 e2 8c 98
1973-11-29 21:33:09 +0000 UTC "1973-11-29 21:33:09 +0000 UTC"
Example (Printers)

Print、Println、およびPrintfは、引数を異なるレイアウトで配置します。この例では、それらの振る舞いを比較することができます。Printlnは常に出力する項目の間に空白を追加しますが、Printは非文字列の引数の間のみ空白を追加し、Printfは正確に指示通りの出力を行います。 Sprint、Sprintln、Sprintf、Fprint、Fprintln、およびFprintfは、ここに示すPrint、Println、およびPrintf関数と同じように動作します。

package main

import (
	"github.com/shogo82148/std/fmt"
	"github.com/shogo82148/std/math"
)

func main() {
	a, b := 3.0, 4.0
	h := math.Hypot(a, b)

	// Printは、どちらも文字列でない場合に引数間に空白を挿入します。
	// 出力に改行は追加されませんので、明示的に追加します。
	fmt.Print("The vector (", a, b, ") has length ", h, ".\n")

	// Printlnは常に引数の間にスペースを挿入するため、
	// この場合にはPrintと同じ出力を生成するためには使用できません。
	// 出力には余分なスペースが含まれています。
	// また、Printlnは常に出力に改行を追加します。
	fmt.Println("The vector (", a, b, ") has length", h, ".")

	// Printfは完全な制御を提供しますが、使用する際にはより複雑です。
	// 出力に改行が追加されないため、フォーマット指定文字列の最後に明示的に追加します。
	fmt.Printf("The vector (%g %g) has length %g.\n", a, b, h)

}
Output:
The vector (3 4) has length 5.
The vector ( 3 4 ) has length 5 .
The vector (3 4) has length 5.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Append added in v1.19.0

func Append(b []byte, a ...any) []byte

Appendはオペランドのデフォルトフォーマットを使用して、フォーマットを行い、結果をバイトスライスに追加し、更新されたスライスを返します。

func Appendf added in v1.19.0

func Appendf(b []byte, format string, a ...any) []byte

Appendfはフォーマット指定子に従ってフォーマットを行い、結果をバイトスライスに追加し、更新されたスライスを返します。

func Appendln added in v1.19.0

func Appendln(b []byte, a ...any) []byte

Appendln はオペランドのデフォルトの書式を使用してフォーマットし、結果をバイトスライスに追加し、更新されたスライスを返します。オペランド間には常にスペースが追加され、改行が追加されます。

func Errorf

func Errorf(format string, a ...any) error

Errorfは書式指定子に従ってフォーマットを行い、errorを満たす値として文字列を返します。

書式指定子に%w動詞とエラー被演算子を含む場合、返されるエラーはUnwrapメソッドを実装し、被演算子を返します。 複数の%w動詞がある場合、返されるエラーは、引数の順序で表示されるすべての%w被演算子を含む[]errorを返します。 エライターフェースを実装していない被演算子を%w動詞として使用することは無効です。それ以外の場合、%w動詞は%vと同義です。

Example

Errorf関数を使用することで、表示形式の機能を使って 詳細なエラーメッセージを作成することができます。

package main

import (
	"github.com/shogo82148/std/fmt"
)

func main() {
	const name, id = "bueller", 17
	err := fmt.Errorf("user %q (id %d) not found", name, id)
	fmt.Println(err.Error())

}
Output:
user "bueller" (id 17) not found

func FormatString added in v1.20.0

func FormatString(state State, verb rune) string

FormatStringは、Stateによってキャプチャされた完全修飾のフォーマットディレクティブを表す文字列を返し、その後に引数の動詞が続きます。(State自体は動詞を含みません。)結果には、先頭にパーセント記号があり、その後にフラグ、幅、および精度が続きます。フラグ、幅、および精度のない場合は省略されます。この関数により、フォーマッタはFormatへの呼び出しをトリガーした元のディレクティブを再構築することができます。

func Fprint

func Fprint(w io.Writer, a ...any) (n int, err error)

Fprint はオペランドのデフォルトのフォーマットを使用してwに書き込みます。 オペランドが文字列でない場合、間にスペースが追加されます。 書き込まれたバイト数と発生した書き込みエラーが返されます。

Example
package main

import (
	"github.com/shogo82148/std/fmt"
	"github.com/shogo82148/std/os"
)

func main() {
	const name, age = "Kim", 22
	n, err := fmt.Fprint(os.Stdout, name, " is ", age, " years old.\n")

	// Fprint の n と err の返り値は、基礎となる io.Writer から返されたものです。
	if err != nil {
		fmt.Fprintf(os.Stderr, "Fprint: %v\n", err)
	}
	fmt.Print(n, " bytes written.\n")

}
Output:
Kim is 22 years old.
21 bytes written.

func Fprintf

func Fprintf(w io.Writer, format string, a ...any) (n int, err error)

Fprintfはフォーマット指定子に従って書式を整え、wに書き込みます。 書き込んだバイト数とエラーの有無を返します。

Example
package main

import (
	"github.com/shogo82148/std/fmt"
	"github.com/shogo82148/std/os"
)

func main() {
	const name, age = "Kim", 22
	n, err := fmt.Fprintf(os.Stdout, "%s is %d years old.\n", name, age)

	// Fprintfからのnとerrの返り値は、基になるio.Writerによって返されたものです。
	if err != nil {
		fmt.Fprintf(os.Stderr, "Fprintf: %v\n", err)
	}
	fmt.Printf("%d bytes written.\n", n)

}
Output:
Kim is 22 years old.
21 bytes written.

func Fprintln

func Fprintln(w io.Writer, a ...any) (n int, err error)

Fprintln はオペランドのデフォルト形式を使用してフォーマットし、w に書き込みます。 オペランドの間には常にスペースが追加され、改行が追加されます。 書き込まれたバイト数と発生した書き込みエラーを返します。

Example
package main

import (
	"github.com/shogo82148/std/fmt"
	"github.com/shogo82148/std/os"
)

func main() {
	const name, age = "Kim", 22
	n, err := fmt.Fprintln(os.Stdout, name, "is", age, "years old.")

	// Fprintlnのnとerrの返り値は、基礎となるio.Writerから返されるものです。
	if err != nil {
		fmt.Fprintf(os.Stderr, "Fprintln: %v\n", err)
	}
	fmt.Println(n, "bytes written.")

}
Output:
Kim is 22 years old.
21 bytes written.

func Fscan

func Fscan(r io.Reader, a ...any) (n int, err error)

Fscan は、r から読み取ったテキストをスキャンし、連続した空白で区切られた値を連続した引数に格納します。改行も空白としてカウントされます。成功したスキャンのアイテム数を返します。引数の数よりも少ない場合、err がなぜエラーが発生したのかを報告します。

func Fscanf

func Fscanf(r io.Reader, format string, a ...any) (n int, err error)

Fscanfはrから読み取ったテキストをスキャンし、 フォーマットに従って連続したスペースで区切られた値を連続した引数に格納します。 成功した解析のアイテム数を返します。 入力の改行はフォーマットの改行と一致する必要があります。

Example
package main

import (
	"github.com/shogo82148/std/fmt"
	"github.com/shogo82148/std/os"
	"github.com/shogo82148/std/strings"
)

func main() {
	var (
		i int
		b bool
		s string
	)
	r := strings.NewReader("5 true gophers")
	n, err := fmt.Fscanf(r, "%d %t %s", &i, &b, &s)
	if err != nil {
		fmt.Fprintf(os.Stderr, "Fscanf: %v\n", err)
	}
	fmt.Println(i, b, s)
	fmt.Println(n)
}
Output:
5 true gophers
3

func Fscanln

func Fscanln(r io.Reader, a ...any) (n int, err error)

FscanlnはFscanに似ていますが、改行でスキャンを終了し、最後の項目の後には改行かEOFが必要です。

Example
package main

import (
	"github.com/shogo82148/std/fmt"
	"github.com/shogo82148/std/io"
	"github.com/shogo82148/std/strings"
)

func main() {
	s := `dmr 1771 1.61803398875
	ken 271828 3.14159`
	r := strings.NewReader(s)
	var a string
	var b int
	var c float64
	for {
		n, err := fmt.Fscanln(r, &a, &b, &c)
		if err == io.EOF {
			break
		}
		if err != nil {
			panic(err)
		}
		fmt.Printf("%d: %s, %d, %f\n", n, a, b, c)
	}
}
Output:
3: dmr, 1771, 1.618034
3: ken, 271828, 3.141590

func Print

func Print(a ...any) (n int, err error)

デフォルトの書式を使用して、オペランドの内容を表示し、標準出力に書き込みます。 オペランドがどちらも文字列でない場合は、オペランド間にスペースが追加されます。 書き込まれたバイト数と発生した書き込みエラーが返されます。

Example
package main

import (
	"github.com/shogo82148/std/fmt"
)

func main() {
	const name, age = "Kim", 22
	fmt.Print(name, " is ", age, " years old.\n")

	// Print が返すエラーについては心配する必要がないというのは慣習です。

}
Output:
Kim is 22 years old.

func Printf

func Printf(format string, a ...any) (n int, err error)

Printfはフォーマット指定子に従ってフォーマットを行い、標準出力に書き込みます。 書き込まれたバイト数とエラーがあれば、それらを返します。

Example
package main

import (
	"github.com/shogo82148/std/fmt"
)

func main() {
	const name, age = "Kim", 22
	fmt.Printf("%s is %d years old.\n", name, age)

	// Printfが返すエラーについては心配しないのが通例です。

}
Output:
Kim is 22 years old.

func Println

func Println(a ...any) (n int, err error)

Printlnは、オペランドのデフォルトのフォーマットを使用して整形し、標準出力に書き込みます。 オペランドとオペランドの間には常にスペースが追加され、改行が追加されます。 書き込まれたバイト数とエラーの有無を返します。

Example
package main

import (
	"github.com/shogo82148/std/fmt"
)

func main() {
	const name, age = "Kim", 22
	fmt.Println(name, "is", age, "years old.")

	// Printlnが返すエラーについては、心配しないのが一般的です。

}
Output:
Kim is 22 years old.

func Scan

func Scan(a ...any) (n int, err error)

Scanは標準入力から読み取ったテキストをスキャンし、連続するスペースで区切られた値を連続した引数に格納します。改行はスペースとして扱われます。スキャンに成功したアイテムの数を返します。引数の数よりも少ない場合、errにはエラーの理由が報告されます。

func Scanf

func Scanf(format string, a ...any) (n int, err error)

Scanfは標準入力から読み取ったテキストをスキャンし、形式に応じて連続したスペースで区切られた値を連続した引数に保存します。成功したスキャンのアイテム数を返します。引数の数よりも少ない場合、エラーが発生した理由がerrに報告されます。入力にある改行は、形式にある改行と一致する必要があります。ただし例外として、動詞%cは常に入力の次のルーンをスキャンします。それがスペース(またはタブなど)や改行であってもです。

func Scanln

func Scanln(a ...any) (n int, err error)

ScanlnはScanに似ていますが、改行でスキャンを停止し、 最後のアイテムの後には改行またはEOFが必要です。

func Sprint

func Sprint(a ...any) string

Sprintは、オペランドのデフォルトのフォーマットを使用して結果の文字列を返します。 オペランドがどちらも文字列でない場合、オペランド間にスペースが追加されます。

Example
package main

import (
	"github.com/shogo82148/std/fmt"
	"github.com/shogo82148/std/io"
	"github.com/shogo82148/std/os"
)

func main() {
	const name, age = "Kim", 22
	s := fmt.Sprint(name, " is ", age, " years old.\n")

	io.WriteString(os.Stdout, s) // シンプルさのためにエラーを無視しています。

}
Output:
Kim is 22 years old.

func Sprintf

func Sprintf(format string, a ...any) string

Sprintfはフォーマット指定子に従ってフォーマットされた文字列を返します。

Example
package main

import (
	"github.com/shogo82148/std/fmt"
	"github.com/shogo82148/std/io"
	"github.com/shogo82148/std/os"
)

func main() {
	const name, age = "Kim", 22
	s := fmt.Sprintf("%s is %d years old.\n", name, age)

	io.WriteString(os.Stdout, s) // 単純化のため、エラーを無視しています。

}
Output:
Kim is 22 years old.

func Sprintln

func Sprintln(a ...any) string

Sprintln はオペランドのデフォルトの書式を使用してフォーマットし、結果の文字列を返します。 オペランド間には常にスペースが追加され、改行が追加されます。

Example
package main

import (
	"github.com/shogo82148/std/fmt"
	"github.com/shogo82148/std/io"
	"github.com/shogo82148/std/os"
)

func main() {
	const name, age = "Kim", 22
	s := fmt.Sprintln(name, "is", age, "years old.")

	io.WriteString(os.Stdout, s) // シンプルさを考慮してエラーを無視します。

}
Output:
Kim is 22 years old.

func Sscan

func Sscan(str string, a ...any) (n int, err error)

Sscanは引数の文字列をスキャンし、連続するスペースで区切られた値を連続する引数に格納します。改行もスペースとして扱われます。正常にスキャンできたアイテムの数を返します。もし正常にスキャンされたアイテムの数が引数の数よりも少ない場合、errがその理由を報告します。

func Sscanf

func Sscanf(str string, format string, a ...any) (n int, err error)

Sscanfは引数文字列をスキャンし、フォーマットによって決まる連続するスペースで区切られた値を連続した引数に格納します。正常に解析されたアイテムの数を返します。 入力の改行は、フォーマットと一致する必要があります。

Example
package main

import (
	"github.com/shogo82148/std/fmt"
)

func main() {
	var name string
	var age int
	n, err := fmt.Sscanf("Kim is 22 years old", "%s is %d years old", &name, &age)
	if err != nil {
		panic(err)
	}
	fmt.Printf("%d: %s, %d\n", n, name, age)

}
Output:
2: Kim, 22

func Sscanln

func Sscanln(str string, a ...any) (n int, err error)

SscanlnはSscanに似ていますが、改行でスキャンを停止し、最後のアイテムの後には改行またはEOFが必要です。

Types

type Formatter

type Formatter interface {
	Format(f State, verb rune)
}

Formatterは、Formatメソッドを持つ任意の値で実装されます。 実装は、Stateとruneの解釈方法を制御し、Sprint()やFprint(f)などを呼び出して出力を生成することができます。

type GoStringer

type GoStringer interface {
	GoString() string
}

GoStringerは、GoStringメソッドを持つ任意の値で実装されており、 その値のGo構文を定義します。 GoStringメソッドは、%#vフォーマットに渡された値を出力するために使用されます。

Example
p1 := Person{
	Name: "Warren",
	Age:  31,
	Addr: &Address{
		City:    "Denver",
		State:   "CO",
		Country: "U.S.A.",
	},
}

// GoString()が実装されていない場合、`fmt.Printf("%#v", p1)`の出力は次のようになります。
// Person{Name:"Warren", Age:0x1f, Addr:(*main.Address)(0x10448240)}
fmt.Printf("%#v\n", p1)

p2 := Person{
	Name: "Theia",
	Age:  4,
}

// GoString()が実装されていなかった場合、`fmt.Printf("%#v", p2)`の出力は以下のようになります
// Person{Name:"Theia", Age:0x4, Addr:(*main.Address)(nil)}
fmt.Printf("%#v\n", p2)
Output:
Person{Name: "Warren", Age: 31, Addr: &Address{City: "Denver", State: "CO", Country: "U.S.A."}}
Person{Name: "Theia", Age: 4}

type ScanState

type ScanState interface {
	// ReadRune reads the next rune (Unicode code point) from the input.
	// If invoked during Scanln, Fscanln, or Sscanln, ReadRune() will
	// return EOF after returning the first '\n' or when reading beyond
	// the specified width.
	ReadRune() (r rune, size int, err error)
	// UnreadRune causes the next call to ReadRune to return the same rune.
	UnreadRune() error
	// SkipSpace skips space in the input. Newlines are treated appropriately
	// for the operation being performed; see the package documentation
	// for more information.
	SkipSpace()
	// Token skips space in the input if skipSpace is true, then returns the
	// run of Unicode code points c satisfying f(c).  If f is nil,
	// !unicode.IsSpace(c) is used; that is, the token will hold non-space
	// characters. Newlines are treated appropriately for the operation being
	// performed; see the package documentation for more information.
	// The returned slice points to shared data that may be overwritten
	// by the next call to Token, a call to a Scan function using the ScanState
	// as input, or when the calling Scan method returns.
	Token(skipSpace bool, f func(rune) bool) (token []byte, err error)
	// Width returns the value of the width option and whether it has been set.
	// The unit is Unicode code points.
	Width() (wid int, ok bool)
	// Because ReadRune is implemented by the interface, Read should never be
	// called by the scanning routines and a valid implementation of
	// ScanState may choose always to return an error from Read.
	Read(buf []byte) (n int, err error)
}

ScanStateはカスタムスキャナーに渡されるスキャナーの状態を表します。 スキャナーは一文字ずつスキャンすることもでき、またScanStateに次のスペース区切りのトークンを見つけるように依頼することもできます。

type Scanner

type Scanner interface {
	Scan(state ScanState, verb rune) error
}

Scannerは、値のスキャンメソッドを持つ任意の値によって実装されており、 入力を値の表現形式でスキャンし、結果をレシーバに格納します。 有用にするために、レシーバはポインタでなければなりません。 スキャンメソッドは、Scan、Scanf、またはScanlnの引数として実装するものです。

type State

type State interface {
	// Write is the function to call to emit formatted output to be printed.
	Write(b []byte) (n int, err error)
	// Width returns the value of the width option and whether it has been set.
	Width() (wid int, ok bool)
	// Precision returns the value of the precision option and whether it has been set.
	Precision() (prec int, ok bool)

	// Flag reports whether the flag c, a character, has been set.
	Flag(c int) bool
}

Stateはカスタムフォーマッタに渡されるプリンタの状態を表します。 io.Writerインターフェースへのアクセスと、オペランドのフォーマット指定子に関するフラグとオプションの情報を提供します。

type Stringer

type Stringer interface {
	String() string
}

Stringerは、Stringメソッドを持つ任意の値によって実装されます。 このメソッドは、その値の「ネイティブ」フォーマットを定義します。 Stringメソッドは、文字列を受け入れる任意のフォーマットや、 Printのような書式のないプリンターにオペランドとして渡される値を表示するために使用されます。

Example
a := Animal{
	Name: "Gopher",
	Age:  2,
}
fmt.Println(a)
Output:
Gopher (2)

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL