Package fmt
https://golang.org/pkg/fmt/
Table of Contents
- Go by Example: String Formatting
func Scan(a ...interface{}) (n int, err error)
- Printing Verbs(like
%d
,%v
, etc) - Scanning with
Scanf
,Fscanf
, and the like
Go by Example: String Formatting tutorial
package main
import "fmt"
type point struct {
x, y int
}
func main() {
p := point{1, 2}
fmt.Printf("00) %v\n", p)
fmt.Printf("01) %+v\n", p)
fmt.Printf("02) %#v\n", p)
fmt.Printf("03) %T\n", p)
fmt.Printf("04) %t\n", true)
fmt.Printf("05) %d\n", 123)
fmt.Printf("06) %b\n", 14)
fmt.Printf("07) %c\n", 33)
fmt.Printf("08) %x\n", 456)
fmt.Printf("09) %f\n", 78.9)
fmt.Printf("10) %e\n", 123400000.0)
fmt.Printf("11) %E\n", 123400000.0)
fmt.Printf("12) %s\n", "\"string\"")
fmt.Printf("13) %q\n", "\"string\"")
fmt.Printf("14) %x\n", "hex this")
fmt.Printf("15) %p\n", &p)
fmt.Printf("16) |%6d|%6d|\n", 12, 345)
fmt.Printf("17) |%6.2f|%6.2f|\n", 1.2, 3.45)
fmt.Printf("18) |%-6.2f|%-6.2f|\n", 1.2, 3.45)
fmt.Printf("19) |%6s|%6s|\n", "foo", "b")
fmt.Printf("20) |%-6s|%-6s|\n", "foo", "b")
}
00) {1 2}
01) {x:1 y:2}
02) main.point{x:1, y:2}
03) main.point
04) true
05) 123
06) 1110
07) !
08) 1c8
09) 78.900000
10) 1.234000e+08
11) 1.234000E+08
12) "string"
13) "\"string\""
14) 6865782074686973
15) 0xc0000180b0
16) | 12| 345|
17) | 1.20| 3.45|
18) |1.20 |3.45 |
19) | foo| b|
20) |foo |b |
Sprintf
and Fprintf
func Scan(a ...interface{}) (n int, err error)
reference
- Reads from standard input
- Stores successive space-separated values into successive arguments.
- Newlines count as space.
- Returns the number of items successfully scanned.
- If that is less than the number of arguments, err will report why.
Printing Verbs(like %d
, %v
, etc) reference
%d |
decimal integer |
%x , %o , %b |
integer in hexadecimal, octal, binary |
%f , %g , %e |
floating-point number: 3.141593 3.141592653589793 3.141593e+00 |
%t |
boolean: true or false |
%c |
rune (Unicode code point) |
%s |
string |
%q |
quoted string "abc" or rune 'c' |
%v |
any value in a natural format |
%T |
type of any value |
%% |
literal percent sign (no operand) |
Scanning with Scanf
, Fscanf
, and the like discussion
- a verb introduced by the
%
character - consumes and parses input;
- A character other than
%
, space, or newline - consumes exactly that input character, which must be present.
- A newline with zero or more spaces before it
- 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
- consumes as many spaces as possible in the input
Space and newline related rules are quite complicated. A related discussion is here.
My overall understanding is:
- Simplify, use just a space for skipping whitespaces
- Use
\n
only when you are sure where\n
comes in the input.