Movatterモバイル変換


[0]ホーム

URL:


fmt

packagestandard library
go1.25.5Latest Latest
Warning

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

Go to latest
Published: Dec 2, 2025 License:BSD-3-ClauseImports:10Imported by:5,485,422

Details

Repository

cs.opensource.google/go/go

Links

Documentation

Overview

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

Printing

The verbs:

General:

%vthe value in a default formatwhen printing structs, the plus flag (%+v) adds field names%#va Go-syntax representation of the value(floating-point infinities and NaNs print as ±Inf and NaN)%Ta Go-syntax representation of the type of the value%%a literal percent sign; consumes no value

Boolean:

%tthe word true or false

Integer:

%bbase 2%cthe character represented by the corresponding Unicode code point%dbase 10%obase 8%Obase 8 with 0o prefix%qa single-quoted character literal safely escaped with Go syntax.%xbase 16, with lower-case letters for a-f%Xbase 16, with upper-case letters for A-F%UUnicode format: U+1234; same as "U+%04X"

Floating-point and complex constituents:

%bdecimalless scientific notation with exponent a power of two,in the manner of strconv.FormatFloat with the 'b' format,e.g. -123456p-78%escientific notation, e.g. -1.234456e+78%Escientific notation, e.g. -1.234456E+78%fdecimal point but no exponent, e.g. 123.456%Fsynonym for %f%g%e for large exponents, %f otherwise. Precision is discussed below.%G%E for large exponents, %F otherwise%xhexadecimal notation (with decimal power of two exponent), e.g. -0x1.23abcp+20%Xupper-case hexadecimal notation, e.g. -0X1.23ABCP+20The exponent is always a decimal integer.For formats other than %b the exponent is at least two digits.

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

%sthe uninterpreted bytes of the string or slice%qa double-quoted string safely escaped with Go syntax%xbase 16, lower-case, two characters per byte%Xbase 16, upper-case, two characters per byte

Slice:

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

Pointer:

%pbase 16 notation, with leading 0xThe %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:                    %tint, int8 etc.:          %duint, uint8 etc.:        %d, %#x if printed with %#vfloat32, complex64, etc: %gstring:                  %schan:                    %ppointer:                 %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 adecimal 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 theunits are always measured in bytes.) Either or both of the flagsmay be replaced with the character '*', causing their values to beobtained 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, precisionlimits the length of the input to be formatted (not the size ofthe output), truncating if necessary. Normally it is measured inrunes, but for these types when formatted with the %x or %X formatit is measured in bytes.

For floating-point values, width sets the minimum width of the field andprecision sets the number of places after the decimal, if appropriate,except that for %g/%G precision sets the maximum number of significantdigits (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, %fand %#g is 6; for %g it is the smallest number of digits necessary to identifythe value uniquely.

For complex numbers, the width and precision apply to the twocomponents independently and the result is parenthesized, so %f appliedto 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 replacementcharacter, U+FFFD, as instrconv.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

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

For each Printf-like function, there is also a Print functionthat takes no format and is equivalent to saying %v for everyoperand. Another variant Println inserts blanks betweenoperands 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{} = 23fmt.Printf("%v\n", i)

will print 23.

Except when printed using the verbs %T and %p, specialformatting considerations apply for operands that implementcertain interfaces. In order of application:

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

2. If an operand implements theFormatter interface, it willbe invoked. In this case the interpretation of verbs and flags iscontrolled by that implementation.

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

If the format (which is implicitly %v forPrintln etc.) is validfor a string (%s %q %x %X), or is %v but not %#v,the following two rules apply:

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

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

For compound operands such as slices and structs, the formatapplies to the elements of each operand, recursively, not to theoperand as a whole. Thus %q will quote each element of a sliceof strings, and %6.2f will control formatting for each elementof 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 stringfunc (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 datastructures, such as a slice that contains itself as an element, ifthat 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 invokeformatting methods such as Error or String on unexported fields.

Explicit argument indexes

InPrintf,Sprintf, andFprintf, the default behavior is for eachformatting verb to format successive arguments passed in the call.However, the notation [n] immediately before the verb indicates that thenth one-indexed argument is to be formatted instead. The same notationbefore a '*' for a width or precision selects the argument index holdingthe value. After processing a bracketed expression [n], subsequent verbswill 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 timesby 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 providinga string to %d, the generated string will contain adescription 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)hiPrintf("%.*s", 4.5, "hi"): %!(BADPREC)hiInvalid 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 sometimesby a single character (the verb) and end with a parenthesizeddescription.

If an Error or String method triggers a panic when called by aprint routine, the fmt package reformats the error messagefrom the panic, decorating it with an indication that it camethrough the fmt package. For example, if a String methodcalls panic("bad"), the resulting formatted message will looklike

%!s(PANIC=bad)

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

Scanning

An analogous set of functions scans formatted text to yieldvalues.Scan,Scanf andScanln read fromos.Stdin;Fscan,Fscanf andFscanln read from a specifiedio.Reader;Sscan,Sscanf andSscanln read from an argument string.

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

Scanln,Fscanln andSscanln stop scanning at a newline andrequire that the items be followed by a newline or EOF.

Scanf,Fscanf, andSscanf parse the arguments according to aformat string, analogous to that ofPrintf. In the text thatfollows, 'space' means any Unicode whitespace characterexcept newline.

In the format string, a verb introduced by the % characterconsumes and parses input; these verbs are described in moredetail below. A character other than %, space, or newline inthe format consumes exactly that input character, which mustbe present. A newline with zero or more spaces before it inthe format string consumes zero or more spaces in the inputfollowed by a single newline or the end of the input. A spacefollowing a newline in the format string consumes zero or morespaces in the input. Otherwise, any run of one or more spacesin the format string consumes as many spaces as possible inthe input. Unless the run of spaces in the format stringappears adjacent to a newline, the run must consume at leastone space from the input or find the end of the input.

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

The verbs behave analogously to those ofPrintf.For example, %x will scan an integer as a hexadecimal number,and %v will scan the default representation format for the value.ThePrintf 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 acceptboth 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: theimplementation of every verb except %c starts by discardingleading spaces from the remaining input, and the %s verb(and %v reading into a string) stops consuming input at the firstspace or newline character.

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

Width is interpreted in the input text but there is nosyntax for scanning with a precision (no %5.2f, just %5f).If width is provided, it applies after leading spaces aretrimmed and specifies the maximum number of runes to readto 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 followedimmediately 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 methodScan (that is, it implements theScanner interface) thatmethod will be used to scan the text for that operand. Also,if the number of arguments scanned is less than the number ofarguments provided, an error is returned.

All arguments to be scanned must be either pointers to basictypes or implementations of theScanner interface.

LikeScanf andFscanf,Sscanf need not consume its entire input.There is no way to recover how much of the input stringSscanf used.

Note:Fscan etc. can read one character (rune) past the inputthey return, which means that a loop calling a scan routinemay skip some of the input. This is usually a problem onlywhen there is no space between input values. If the readerprovided toFscan implements ReadRune, that method will be usedto read characters. If the reader also implements UnreadRune,that method will be used to save the character and successivecalls will not lose data. To attach ReadRune and UnreadRunemethods to a reader without that capability, usebufio.NewReader.

Example (Formats)

These examples demonstrate the basics of printing using a format string. Printf,Sprintf, and Fprintf all take a format string that specifies how to format thesubsequent arguments. For example, %d (we call that a 'verb') says to print thecorresponding argument, which must be an integer (or something containing aninteger, such as a slice of ints) in decimal. The verb %v ('v' for 'value')always formats the argument in its default form, just how Print or Println wouldshow it. The special verb %T ('T' for 'Type') prints the type of the argumentrather than its value. The examples are not exhaustive; see the package commentfor all the details.

package mainimport ("fmt""math""time")func main() {// A basic set of examples showing that %v is the default format, in this// case decimal for integers, which can be explicitly requested with %d;// the output is just what Println generates.integer := 23// Each of these prints "23" (without the quotes).fmt.Println(integer)fmt.Printf("%v\n", integer)fmt.Printf("%d\n", integer)// The special verb %T shows the type of an item rather than its value.fmt.Printf("%T %T\n", integer, &integer)// Result: int *int// Println(x) is the same as Printf("%v\n", x) so we will use only Printf// in the following examples. Each one demonstrates how to format values of// a particular type, such as integers or strings. We start each format// string with %v to show the default output and follow that with one or// more custom formats.// Booleans print as "true" or "false" with %v or %t.truth := truefmt.Printf("%v %t\n", truth, truth)// Result: true true// Integers print as decimals with %v and %d,// or in hex with %x, octal with %o, or binary with %b.answer := 42fmt.Printf("%v %d %x %o %b\n", answer, answer, answer, answer, answer)// Result: 42 42 2a 52 101010// Floats have multiple formats: %v and %g print a compact representation,// while %f prints a decimal point and %e uses exponential notation. The// format %6.2f used here shows how to set the width and precision to// control the appearance of a floating-point value. In this instance, 6 is// the total width of the printed text for the value (note the extra spaces// in the output) and 2 is the number of decimal places to show.pi := math.Pifmt.Printf("%v %g %.2f (%6.2f) %e\n", pi, pi, pi, pi, pi)// Result: 3.141592653589793 3.141592653589793 3.14 (  3.14) 3.141593e+00// Complex numbers format as parenthesized pairs of floats, with an 'i'// after the imaginary part.point := 110.7 + 22.5ifmt.Printf("%v %g %.2f %.2e\n", point, point, point, point)// Result: (110.7+22.5i) (110.7+22.5i) (110.70+22.50i) (1.11e+02+2.25e+01i)// Runes are integers but when printed with %c show the character with that// Unicode value. The %q verb shows them as quoted characters, %U as a// hex Unicode code point, and %#U as both a code point and a quoted// printable form if the rune is printable.smile := '😀'fmt.Printf("%v %d %c %q %U %#U\n", smile, smile, smile, smile, smile, smile)// Result: 128512 128512 😀 '😀' U+1F600 U+1F600 '😀'// Strings are formatted with %v and %s as-is, with %q as quoted strings,// and %#q as backquoted strings.placeholders := `foo "bar"`fmt.Printf("%v %s %q %#q\n", placeholders, placeholders, placeholders, placeholders)// Result: foo "bar" foo "bar" "foo \"bar\"" `foo "bar"`// Maps formatted with %v show keys and values in their default formats.// The %#v form (the # is called a "flag" in this context) shows the map in// the Go source format. Maps are printed in a consistent order, sorted// by the values of the keys.isLegume := map[string]bool{"peanut":    true,"dachshund": false,}fmt.Printf("%v %#v\n", isLegume, isLegume)// Result: map[dachshund:false peanut:true] map[string]bool{"dachshund":false, "peanut":true}// Structs formatted with %v show field values in their default formats.// The %+v form shows the fields by name, while %#v formats the struct in// Go source format.person := struct {Name stringAge  int}{"Kim", 22}fmt.Printf("%v %+v %#v\n", person, person, person)// Result: {Kim 22} {Name:Kim Age:22} struct { Name string; Age int }{Name:"Kim", Age:22}// The default format for a pointer shows the underlying value preceded by// an ampersand. The %p verb prints the pointer value in hex. We use a// typed nil for the argument to %p here because the value of any non-nil// pointer would change from run to run; run the commented-out Printf// call yourself to see.pointer := &personfmt.Printf("%v %p\n", pointer, (*int)(nil))// Result: &{Kim 22} 0x0// fmt.Printf("%v %p\n", pointer, pointer)// Result: &{Kim 22} 0x010203 // See comment above.// Arrays and slices are formatted by applying the format to each element.greats := [5]string{"Kitano", "Kobayashi", "Kurosawa", "Miyazaki", "Ozu"}fmt.Printf("%v %q\n", greats, greats)// Result: [Kitano Kobayashi Kurosawa Miyazaki Ozu] ["Kitano" "Kobayashi" "Kurosawa" "Miyazaki" "Ozu"]kGreats := greats[:3]fmt.Printf("%v %q %#v\n", kGreats, kGreats, kGreats)// Result: [Kitano Kobayashi Kurosawa] ["Kitano" "Kobayashi" "Kurosawa"] []string{"Kitano", "Kobayashi", "Kurosawa"}// Byte slices are special. Integer verbs like %d print the elements in// that format. The %s and %q forms treat the slice like a string. The %x// verb has a special form with the space flag that puts a space between// the bytes.cmd := []byte("a⌘")fmt.Printf("%v %d %s %q %x % x\n", cmd, cmd, cmd, cmd, cmd, cmd)// Result: [97 226 140 152] [97 226 140 152] a⌘ "a⌘" 61e28c98 61 e2 8c 98// Types that implement Stringer are printed the same as strings. Because// Stringers return a string, we can print them using a string-specific// verb such as %q.now := time.Unix(123456789, 0).UTC() // time.Time implements fmt.Stringer.fmt.Printf("%v %q\n", now, now)// Result: 1973-11-29 21:33:09 +0000 UTC "1973-11-29 21:33:09 +0000 UTC"}
Output:232323int *inttrue true42 42 2a 52 1010103.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 981973-11-29 21:33:09 +0000 UTC "1973-11-29 21:33:09 +0000 UTC"

Example (Printers)

Print, Println, and Printf lay out their arguments differently. In this examplewe can compare their behaviors. Println always adds blanks between the items itprints, while Print adds blanks only between non-string arguments and Printfdoes exactly what it is told.Sprint, Sprintln, Sprintf, Fprint, Fprintln, and Fprintf behave the same astheir corresponding Print, Println, and Printf functions shown here.

package mainimport ("fmt""math")func main() {a, b := 3.0, 4.0h := math.Hypot(a, b)// Print inserts blanks between arguments when neither is a string.// It does not add a newline to the output, so we add one explicitly.fmt.Print("The vector (", a, b, ") has length ", h, ".\n")// Println always inserts spaces between its arguments,// so it cannot be used to produce the same output as Print in this case;// its output has extra spaces.// Also, Println always adds a newline to the output.fmt.Println("The vector (", a, b, ") has length", h, ".")// Printf provides complete control but is more complex to use.// It does not add a newline to the output, so we add one explicitly// at the end of the format specifier string.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

funcAppendadded ingo1.19

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

Append formats using the default formats for its operands, appends the result tothe byte slice, and returns the updated slice.

funcAppendfadded ingo1.19

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

Appendf formats according to a format specifier, appends the result to the byteslice, and returns the updated slice.

funcAppendlnadded ingo1.19

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

Appendln formats using the default formats for its operands, appends the resultto the byte slice, and returns the updated slice. Spaces are always addedbetween operands and a newline is appended.

funcErrorf

func Errorf(formatstring, a ...any)error

Errorf formats according to a format specifier and returns the string as avalue that satisfies error.

If the format specifier includes a %w verb with an error operand,the returned error will implement an Unwrap method returning the operand.If there is more than one %w verb, the returned error will implement anUnwrap method returning a []error containing all the %w operands in theorder they appear in the arguments.It is invalid to supply the %w verb with an operand that does not implementthe error interface. The %w verb is otherwise a synonym for %v.

Example

The Errorf function lets us use formatting featuresto create descriptive error messages.

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

funcFormatStringadded ingo1.20

func FormatString(stateState, verbrune)string

FormatString returns a string representing the fully qualified formattingdirective captured by theState, followed by the argument verb. (State does notitself contain the verb.) The result has a leading percent sign followed by anyflags, the width, and the precision. Missing flags, width, and precision areomitted. This function allows aFormatter to reconstruct the originaldirective triggering the call to Format.

funcFprint

func Fprint(wio.Writer, a ...any) (nint, errerror)

Fprint formats using the default formats for its operands and writes to w.Spaces are added between operands when neither is a string.It returns the number of bytes written and any write error encountered.

Example
package mainimport ("fmt""os")func main() {const name, age = "Kim", 22n, err := fmt.Fprint(os.Stdout, name, " is ", age, " years old.\n")// The n and err return values from Fprint are// those returned by the underlying 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.

funcFprintf

func Fprintf(wio.Writer, formatstring, a ...any) (nint, errerror)

Fprintf formats according to a format specifier and writes to w.It returns the number of bytes written and any write error encountered.

Example
package mainimport ("fmt""os")func main() {const name, age = "Kim", 22n, err := fmt.Fprintf(os.Stdout, "%s is %d years old.\n", name, age)// The n and err return values from Fprintf are// those returned by the underlying 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.

funcFprintln

func Fprintln(wio.Writer, a ...any) (nint, errerror)

Fprintln formats using the default formats for its operands and writes to w.Spaces are always added between operands and a newline is appended.It returns the number of bytes written and any write error encountered.

Example
package mainimport ("fmt""os")func main() {const name, age = "Kim", 22n, err := fmt.Fprintln(os.Stdout, name, "is", age, "years old.")// The n and err return values from Fprintln are// those returned by the underlying 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.

funcFscan

func Fscan(rio.Reader, a ...any) (nint, errerror)

Fscan scans text read from r, storing successive space-separatedvalues into successive arguments. Newlines count as space. Itreturns the number of items successfully scanned. If that is lessthan the number of arguments, err will report why.

funcFscanf

func Fscanf(rio.Reader, formatstring, a ...any) (nint, errerror)

Fscanf scans text read from r, storing successive space-separatedvalues into successive arguments as determined by the format. Itreturns the number of items successfully parsed.Newlines in the input must match newlines in the format.

Example
package mainimport ("fmt""os""strings")func main() {var (i intb bools 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 gophers3

funcFscanln

func Fscanln(rio.Reader, a ...any) (nint, errerror)

Fscanln is similar toFscan, but stops scanning at a newline andafter the final item there must be a newline or EOF.

Example
package mainimport ("fmt""io""strings")func main() {s := `dmr 1771 1.61803398875ken 271828 3.14159`r := strings.NewReader(s)var a stringvar b intvar c float64for {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.6180343: ken, 271828, 3.141590

funcPrint

func Print(a ...any) (nint, errerror)

Print formats using the default formats for its operands and writes to standard output.Spaces are added between operands when neither is a string.It returns the number of bytes written and any write error encountered.

Example
package mainimport ("fmt")func main() {const name, age = "Kim", 22fmt.Print(name, " is ", age, " years old.\n")// It is conventional not to worry about any// error returned by Print.}
Output:Kim is 22 years old.

funcPrintf

func Printf(formatstring, a ...any) (nint, errerror)

Printf formats according to a format specifier and writes to standard output.It returns the number of bytes written and any write error encountered.

Example
package mainimport ("fmt")func main() {const name, age = "Kim", 22fmt.Printf("%s is %d years old.\n", name, age)// It is conventional not to worry about any// error returned by Printf.}
Output:Kim is 22 years old.

funcPrintln

func Println(a ...any) (nint, errerror)

Println formats using the default formats for its operands and writes to standard output.Spaces are always added between operands and a newline is appended.It returns the number of bytes written and any write error encountered.

Example
package mainimport ("fmt")func main() {const name, age = "Kim", 22fmt.Println(name, "is", age, "years old.")// It is conventional not to worry about any// error returned by Println.}
Output:Kim is 22 years old.

funcScan

func Scan(a ...any) (nint, errerror)

Scan scans text read from standard input, storing successivespace-separated values into successive arguments. Newlines countas space. It returns the number of items successfully scanned.If that is less than the number of arguments, err will report why.

funcScanf

func Scanf(formatstring, a ...any) (nint, errerror)

Scanf scans text read from standard input, storing successivespace-separated values into successive arguments as determined bythe format. It returns the number of items successfully scanned.If that is less than the number of arguments, err will report why.Newlines in the input must match newlines in the format.The one exception: the verb %c always scans the next rune in theinput, even if it is a space (or tab etc.) or newline.

funcScanln

func Scanln(a ...any) (nint, errerror)

Scanln is similar toScan, but stops scanning at a newline andafter the final item there must be a newline or EOF.

funcSprint

func Sprint(a ...any)string

Sprint formats using the default formats for its operands and returns the resulting string.Spaces are added between operands when neither is a string.

Example
package mainimport ("fmt""io""os")func main() {const name, age = "Kim", 22s := fmt.Sprint(name, " is ", age, " years old.\n")io.WriteString(os.Stdout, s) // Ignoring error for simplicity.}
Output:Kim is 22 years old.

funcSprintf

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

Sprintf formats according to a format specifier and returns the resulting string.

Example
package mainimport ("fmt""io""os")func main() {const name, age = "Kim", 22s := fmt.Sprintf("%s is %d years old.\n", name, age)io.WriteString(os.Stdout, s) // Ignoring error for simplicity.}
Output:Kim is 22 years old.

funcSprintln

func Sprintln(a ...any)string

Sprintln formats using the default formats for its operands and returns the resulting string.Spaces are always added between operands and a newline is appended.

Example
package mainimport ("fmt""io""os")func main() {const name, age = "Kim", 22s := fmt.Sprintln(name, "is", age, "years old.")io.WriteString(os.Stdout, s) // Ignoring error for simplicity.}
Output:Kim is 22 years old.

funcSscan

func Sscan(strstring, a ...any) (nint, errerror)

Sscan scans the argument string, storing successive space-separatedvalues into successive arguments. Newlines count as space. Itreturns the number of items successfully scanned. If that is lessthan the number of arguments, err will report why.

funcSscanf

func Sscanf(strstring, formatstring, a ...any) (nint, errerror)

Sscanf scans the argument string, storing successive space-separatedvalues into successive arguments as determined by the format. Itreturns the number of items successfully parsed.Newlines in the input must match newlines in the format.

Example
package mainimport ("fmt")func main() {var name stringvar age intn, 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

funcSscanln

func Sscanln(strstring, a ...any) (nint, errerror)

Sscanln is similar toSscan, but stops scanning at a newline andafter the final item there must be a newline or EOF.

Types

typeFormatter

type Formatter interface {Format(fState, verbrune)}

Formatter is implemented by any value that has a Format method.The implementation controls howState and rune are interpreted,and may callSprint orFprint(f) etc. to generate its output.

typeGoStringer

type GoStringer interface {GoString()string}

GoStringer is implemented by any value that has a GoString method,which defines the Go syntax for that value.The GoString method is used to print values passed as an operandto a %#v format.

Example
package mainimport ("fmt")// Address has a City, State and a Country.type Address struct {City    stringState   stringCountry string}// Person has a Name, Age and Address.type Person struct {Name stringAge  uintAddr *Address}// GoString makes Person satisfy the GoStringer interface.// The return value is valid Go code that can be used to reproduce the Person struct.func (p Person) GoString() string {if p.Addr != nil {return fmt.Sprintf("Person{Name: %q, Age: %d, Addr: &Address{City: %q, State: %q, Country: %q}}", p.Name, int(p.Age), p.Addr.City, p.Addr.State, p.Addr.Country)}return fmt.Sprintf("Person{Name: %q, Age: %d}", p.Name, int(p.Age))}func main() {p1 := Person{Name: "Warren",Age:  31,Addr: &Address{City:    "Denver",State:   "CO",Country: "U.S.A.",},}// If GoString() wasn't implemented, the output of `fmt.Printf("%#v", p1)` would be similar to// Person{Name:"Warren", Age:0x1f, Addr:(*main.Address)(0x10448240)}fmt.Printf("%#v\n", p1)p2 := Person{Name: "Theia",Age:  4,}// If GoString() wasn't implemented, the output of `fmt.Printf("%#v", p2)` would be similar to// 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}

typeScanState

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() (rrune, sizeint, errerror)// 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(skipSpacebool, f func(rune)bool) (token []byte, errerror)// Width returns the value of the width option and whether it has been set.// The unit is Unicode code points.Width() (widint, okbool)// 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) (nint, errerror)}

ScanState represents the scanner state passed to custom scanners.Scanners may do rune-at-a-time scanning or ask the ScanStateto discover the next space-delimited token.

typeScanner

type Scanner interface {Scan(stateScanState, verbrune)error}

Scanner is implemented by any value that has a Scan method, which scansthe input for the representation of a value and stores the result in thereceiver, which must be a pointer to be useful. The Scan method is calledfor any argument toScan,Scanf, orScanln that implements it.

typeState

type State interface {// Write is the function to call to emit formatted output to be printed.Write(b []byte) (nint, errerror)// Width returns the value of the width option and whether it has been set.Width() (widint, okbool)// Precision returns the value of the precision option and whether it has been set.Precision() (precint, okbool)// Flag reports whether the flag c, a character, has been set.Flag(cint)bool}

State represents the printer state passed to custom formatters.It provides access to theio.Writer interface plus information aboutthe flags and options for the operand's format specifier.

typeStringer

type Stringer interface {String()string}

Stringer is implemented by any value that has a String method,which defines the “native” format for that value.The String method is used to print values passed as an operandto any format that accepts a string or to an unformatted printersuch asPrint.

Example
package mainimport ("fmt")// Animal has a Name and an Age to represent an animal.type Animal struct {Name stringAge  uint}// String makes Animal satisfy the Stringer interface.func (a Animal) String() string {return fmt.Sprintf("%v (%d)", a.Name, a.Age)}func main() {a := Animal{Name: "Gopher",Age:  2,}fmt.Println(a)}
Output:Gopher (2)

Source Files

View all Source files

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f orF : Jump to
y orY : Canonical URL
go.dev uses cookies from Google to deliver and enhance the quality of its services and to analyze traffic.Learn more.

[8]ページ先頭

©2009-2025 Movatter.jp