FMT usage in Golang

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed. Functions and methods in the FMT package



This article turns from Golang Learning-fmt pack:
Http://www.cnblogs.com/golove/p/3286303.html



Format.go

------------------------------------------------------------

fprintf the parameter list A into the placeholder for format string
and writes the completed result to W, returns the number of bytes written
Func fprintf (w io. Writer, format string, a ... interface{}) (n int, err error)

Printf fills in the parameter list a placeholder in format string
And writes the completed results to the OS. Stdout, returns the number of bytes written
Func Printf (format string, a ... interface{}) (n int, err error)

Sprintf the parameter list A into the placeholder for format string
Return the completed results
Func Sprintf (format string, a ... interface{}) string

Errorf the parameter list A into the placeholder for format string
and converts the completed result to the error type returned
Func Errorf (format string, a ... interface{}) error

------------------------------------------------------------

Fprint converts each parameter in argument list A to a string format and writes to W
Each parameter is separated by a space, and the number of bytes written is returned
Func fprint (w io. Writer, a ... interface{}) (n int, err error)

Print converts each parameter in parameter list A to a string format and writes to the OS. In Stdout
Each parameter is separated by a space, and the number of bytes written is returned
Func Print (A ... interface{}) (n int, err error)

Sprint converts each parameter in argument list A to a string format and returns
Each parameter is separated by a space
Func Sprint (A ... interface{}) string

------------------------------------------------------------

Fprintln on the basis of fprint, and then writes a newline character to W
Func fprintln (w io. Writer, a ... interface{}) (n int, err error)

Println on the Print basis, then to the OS. Write a line break in Stdout
Func Println (A ... interface{}) (n int, err error)

Sprintln on the basis of the Sprint, add a newline character at the end of the return value
Func sprintln (A ... interface{}) string

------------------------------------------------------------

Example
Func Main () {
Fmt. fprintf (OS. Stdout, "%08b\n", 32)//00100000
Fmt. Printf ("%08b\n", 32)//00100000
Fmt. Print (FMT. Sprintf ("%08b\n", 32))//00100000
Fmt. Print (FMT. Errorf ("%08b\n", 32))//00100000

Fmt. Fprint (OS. Stdout, "A")
Fmt. Print ("B")
Fmt. Print (FMT. Sprint ("C"))
Abc

Fmt. Print ("\ n")

Fmt. Fprintln (OS. Stdout, "a")//A
Fmt. Println ("B")//b
Fmt. Print (FMT. Sprintln ("C"))//C
}

------------------------------------------------------------

Formatter to implement custom format output for an object
Type Formatter Interface {
Format is used to handle the output when an object encounters a C tag (c equals s in%s)
F is used to obtain information such as the width, precision, and extension marks of the placeholder, while achieving the final output
C is the token to be processed
Format (f State, C rune)
}

State used to get the status of a placeholder, including information such as width, precision, extended markup, and so on
The output of the formatted string is also implemented
Type state Interface {
Write is used to output a formatted string to the specified object
Output to a different location depending on the Print function (fprintf,printf,sprintf)
Write (b []byte) (ret int, err error)
Width returns whether the placeholder value (WID) and width are set (OK)
Width () (wid int, OK bool)
Precision returns the precision value of the placeholder (PREC) and whether the precision is set (OK)
Precision () (prec int, OK bool)
Flag returns whether the extension token C (a character, such as # in% #s) has been set
Flag (c int) bool
}

Type Stringer Interface {
String gets the text form of the object
String () string
}

Type Gostringer Interface {
Gostring gets the text form of the object's Go syntax (output in% #v format)
Gostring () string
}

------------------------------------------------------------

Example
Type USTR string

Func (US Ustr) string () string {
return string (US) + "custom Format"
}

Func (US Ustr) gostring () string {
return string (US) + "Go format"
}

Func (US Ustr) Format (f FMT. State, C rune) {
Switch C {
Case ' m ', ' m ':
F.write ([]byte (US + "\ n extension tag: [")]
If F.flag ('-') {
F.write ([]byte ("-"))
}
If F.flag (' + ') {
F.write ([]byte ("+"))
}
If F.flag (' # ') {
F.write ([]byte ("#"))
}
If F.flag (") {
F.write ([]byte ("Space"))
}
If F.flag (' 0 ') {
F.write ([]byte ("0"))
}
F.write ([]byte ("]\n"))
If w, wok: = F.width (); Wok {
F.write ([]byte ("Width value:" + FMT. Sprint (w) + "\ n"))
}
If p, Pok: = F.precision (); Pok {
F.write ([]byte ("Precision value:" + FMT. Sprint (p)))
}
Case ' V '://If you use the Format function, you must handle all formats yourself, including% #v
If F.flag (' # ') {
F.write ([]byte (US. Gostring ()))
} else {
F.write ([]byte (US. String ()))
}
Default://If you use the Format function, you must handle the defaults output yourself
F.write ([]byte (US. String ()))
}
}

Func Main () {
US: = Ustr ("Hello world!")
Fmt. Printf ("% 0-+ #8.5m\n", US)
Hello world!
Extension tag: [-+ # space 0]
Width Value: 8
Precision Value: 5
Fmt. Println (US)
Hello world! Custom formats
Fmt. Printf ("% #v \ n", US)
Hello world! Go format
}



============================================================



Scan.go

------------------------------------------------------------

FSCANF is used to scan data in R and format specified by format
Fill in parameter list A with scanned data
When the data in R is fully scanned or the length of the scan exceeds the length specified by format
The scan is stopped (newline characters are treated as whitespace).
Func Fscanf (R io. Reader, format string, a ... interface{}) (n int, err error)

Func Main () {
S: = Strings. Newreader ("My Name is Golang, 4 years old this year")
var name string
var age int
Note: You must pass the pointer &name here, &age
There must be a space before and after the data to get
Fmt. FSCANF (S, "My name is%s, this year is%d years old", &name, &age)
Fmt. Printf ("%s%d", name, age)
Golang 4
}

The Scanf is used to scan the OS. The data in the Stdin, and the format specified by format
Fill in parameter list A with scanned data
When the data in R is fully scanned or the length of the scan exceeds the length specified by format
The scan is stopped (newline characters are treated as whitespace).
Func Scanf (format string, a ... interface{}) (n int, err error)

Func Main () {
var name string
var age int
Note: You must pass the pointer &name here, &age
There must be a space before and after the data to get
Fmt. SCANF ("%s%d", &name, &age)
In console input: Golang 4
Fmt. Printf ("My name is%s, this year is%d", name, age)
My name is Golang, 4 years old this year.
}

The Sscanf is used to scan data in STR and format specified by format
Fill in parameter list A with scanned data
When the data in R is fully scanned or the length of the scan exceeds the length specified by format
The scan is stopped (newline characters are treated as whitespace).
Func Sscanf (str string, format string, a ... interface{}) (n int, err error)

Func Main () {
S: = "My name is Golang, 4 years old this year"
var name string
var age int
Note: You must pass the pointer &name here, &age
There must be a space before and after the data to get
Fmt. SSCANF (S, "My name is%s, this year is%d years old", &name, &age)
Fmt. Printf ("%s%d", name, age)
Golang 4
}

------------------------------------------------------------

Fscan is used to scan data in R and split the data with a space separator
Then fill in the parameter list A
When the data in R is completely scanned or the parameter list A is all filled out
The scan is stopped (newline characters are treated as whitespace).
Func Fscan (R io. Reader, a ... interface{}) (n int, err error)

Scan is used for scanning the OS. Data in the Stdin and splits the data with a space separator
Then fill in the parameter list A
When the data in R is completely scanned or the parameter list A is all filled out
The scan is stopped (newline characters are treated as whitespace).
Func Scan (A ... interface{}) (n int, err error)

Sscan is used to scan data in STR and split the data with a space separator
Then fill in the parameter list A
When the data in R is completely scanned or the parameter list A is all filled out
The scan is stopped (newline characters are treated as whitespace).
Func Sscan (str string, a ... interface{}) (n int, err error)

------------------------------------------------------------

FSCANLN is used to scan data in R and split the data with a space separator
Then fill in the parameter list A
When the scan process encounters ' \ n ' or the parameter list A is fully completed
Stop the scan
Func fscanln (R io. Reader, a ... interface{}) (n int, err error)

The SCANLN is used to scan the OS. Data in the Stdin and splits the data with a space separator
Then fill in the parameter list A
When the scan process encounters ' \ n ' or the parameter list A is fully completed
Stop the scan
Func Scanln (A ... interface{}) (n int, err error)

SSCANLN is used to scan data in STR and split the data with a space separator
Then fill in the parameter list A
When the scan process encounters ' \ n ' or the parameter list A is fully completed
Stop the scan
Func sscanln (str string, a ... interface{}) (n int, err error)

------------------------------------------------------------

ScanState will return the scan status to the custom Scanner
Scanner may do real-time scanning of characters
Or get tokens separated by a space by ScanState
Type ScanState Interface {
Readrune reading a Unicode character from an input object
If the method is called in Scanln, Fscanln, or Sscanln
This method returns EOF when it encounters ' \ n ' or reads more than the specified width
Readrune () (R rune, size int, err error)
Unreadrune undoing the last Readrune operation
Unreadrune () Error
Skipspace skipping spaces in the input data
In Scanln, FSCANLN, SSCANLN operations, newline characters are treated as EOF.
In other Scan operations, newline characters are treated as spaces.
Skipspace ()
If the parameter skipspace is true, Token skips the spaces in the input data
The successive characters that satisfy the function f are then returned, and if F is nil,!unicode is used. IsSpace to replace F
In Scanln, FSCANLN, SSCANLN operations, newline characters are treated as EOF.
In other Scan operations, newline characters are treated as spaces.
The token returned is a slice, and the returned data may be modified the next time token is called
Token (skipspace bool, F func (rune) bool) (token []byte, err Error)
Width returns the value and width value are set
Width () (wid int, OK bool)
Because Readrune is already implemented through an interface, Read may never be called by the Scan routine
An ScanState implementation may choose to discard the Read method, leaving it always returning an error message
Read (buf []byte) (n int, err error)
}

Scanner for implementing custom format scans of objects
Type Scanner Interface {
Scan is used to process how the object is scanned when it encounters a C tag (c is equivalent to s in%s)
State is used to process scan status
C is the token to be processed
Scan (state ScanState, verb rune) error
}





Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.