форматирование строк

This commit is contained in:
badkaktus 2019-10-09 16:35:15 +03:00
parent afe89e6383
commit 7a6019d8db
2 changed files with 48 additions and 50 deletions

View File

@ -43,7 +43,7 @@ Panic
Defer Defer
Функции коллекции (Collection Functions) Функции коллекции (Collection Functions)
Строковые функции (String Functions) Строковые функции (String Functions)
String Formatting Форматирование строк (String Formatting)
Regular Expressions Regular Expressions
JSON JSON
XML XML

View File

@ -1,6 +1,6 @@
// Go offers excellent support for string formatting in // Go предлагает отличную поддержку форматирования строк
// the `printf` tradition. Here are some examples of // с помощью `printf`. Вот несколько примеров типичных
// common string formatting tasks. // задач форматирования строк.
package main package main
@ -15,96 +15,94 @@ type point struct {
func main() { func main() {
// Go offers several printing "verbs" designed to // Go предлагает несколько “глаголов” созданных для
// format general Go values. For example, this prints // форматирования общих Go значений. Например,
// an instance of our `point` struct. // это выведет инстанс нашей `point` структуры.
p := point{1, 2} p := point{1, 2}
fmt.Printf("%v\n", p) fmt.Printf("%v\n", p)
// If the value is a struct, the `%+v` variant will // Если значение является структурой, запись `%+v`
// include the struct's field names. // выведет названия полей структуры.
fmt.Printf("%+v\n", p) fmt.Printf("%+v\n", p)
// The `%#v` variant prints a Go syntax representation // Вариант `%#v` печатает синтаксическое представление
// of the value, i.e. the source code snippet that // Go, то есть фрагмент исходного кода, который будет
// would produce that value. // генерировать это значение.
fmt.Printf("%#v\n", p) fmt.Printf("%#v\n", p)
// To print the type of a value, use `%T`. // Для вывода типа значения, используйте `%T`.
fmt.Printf("%T\n", p) fmt.Printf("%T\n", p)
// Formatting booleans is straight-forward. // Форматирование логических значений не вызывает затруднений.
fmt.Printf("%t\n", true) fmt.Printf("%t\n", true)
// There are many options for formatting integers. // Возможно большое количество опций для форматирования
// Use `%d` for standard, base-10 formatting. // целых чисел. Используйте `%d` для стандартного,
// десятеричного вывода.
fmt.Printf("%d\n", 123) fmt.Printf("%d\n", 123)
// This prints a binary representation. // Бинарный вывод
fmt.Printf("%b\n", 14) fmt.Printf("%b\n", 14)
// This prints the character corresponding to the // Вывод символа, соответсвующего заданному числу.
// given integer.
fmt.Printf("%c\n", 33) fmt.Printf("%c\n", 33)
// `%x` provides hex encoding. // `%x` - шестнадцатиричное значение.
fmt.Printf("%x\n", 456) fmt.Printf("%x\n", 456)
// There are also several formatting options for // Так же есть несколько вариантов форматирования
// floats. For basic decimal formatting use `%f`. // чисел с плавающей точкой. Стандартный вывод `%f`.
fmt.Printf("%f\n", 78.9) fmt.Printf("%f\n", 78.9)
// `%e` and `%E` format the float in (slightly // `%e` и `%E` приводит числло с плавающей точкой
// different versions of) scientific notation. // к экспоненциальному представлению.
fmt.Printf("%e\n", 123400000.0) fmt.Printf("%e\n", 123400000.0)
fmt.Printf("%E\n", 123400000.0) fmt.Printf("%E\n", 123400000.0)
// For basic string printing use `%s`. // Для стандартного вывода строк используйте `%s`.
fmt.Printf("%s\n", "\"string\"") fmt.Printf("%s\n", "\"string\"")
// To double-quote strings as in Go source, use `%q`. // Для двойных ковычек как в исходниках Go, используйте `%q`.
fmt.Printf("%q\n", "\"string\"") fmt.Printf("%q\n", "\"string\"")
// As with integers seen earlier, `%x` renders // Так же как и с целочисленными ранее, `%x` отображает
// the string in base-16, with two output characters // строку в виде шестнадцатеричного исчисления, с двумя
// per byte of input. // символами вывода за каждый байт ввода.
fmt.Printf("%x\n", "hex this") fmt.Printf("%x\n", "hex this")
// To print a representation of a pointer, use `%p`. // Чтобы вывести ссылку на указатель, используйте `%p`.
fmt.Printf("%p\n", &p) fmt.Printf("%p\n", &p)
// When formatting numbers you will often want to // При форматировании чисел вам часто захочется
// control the width and precision of the resulting // контролировать ширину и точность получаемого значения.
// figure. To specify the width of an integer, use a // Чтобы указать ширину целого числа, используйте
// number after the `%` in the verb. By default the // число после `%`. По-умолчанию результат будет
// result will be right-justified and padded with // выровнен по правому краю и дополнен пробелами.
// spaces.
fmt.Printf("|%6d|%6d|\n", 12, 345) fmt.Printf("|%6d|%6d|\n", 12, 345)
// You can also specify the width of printed floats, // Вы также можете указать ширину чисел с плавающей точкой,
// though usually you'll also want to restrict the // также вы можете ограничить десятичную точность
// decimal precision at the same time with the // одновременно с помощью синтаксиса `ширина.точность`.
// width.precision syntax.
fmt.Printf("|%6.2f|%6.2f|\n", 1.2, 3.45) fmt.Printf("|%6.2f|%6.2f|\n", 1.2, 3.45)
// To left-justify, use the `-` flag. // Для выравнивания по левому краю используйте флаг `-`.
fmt.Printf("|%-6.2f|%-6.2f|\n", 1.2, 3.45) fmt.Printf("|%-6.2f|%-6.2f|\n", 1.2, 3.45)
// You may also want to control width when formatting // Вы также можете контролировать ширину при форматировании
// strings, especially to ensure that they align in // строк, особенно для обеспечения их выравнивания в табличном
// table-like output. For basic right-justified width. // выводе. Стандартное выравнивание по правому краю.
fmt.Printf("|%6s|%6s|\n", "foo", "b") fmt.Printf("|%6s|%6s|\n", "foo", "b")
// To left-justify use the `-` flag as with numbers. // Для выравнивания по левому краю используйте флаг `-`.
fmt.Printf("|%-6s|%-6s|\n", "foo", "b") fmt.Printf("|%-6s|%-6s|\n", "foo", "b")
// So far we've seen `Printf`, which prints the // До сих пор мы видели `Printf`, который печатает
// formatted string to `os.Stdout`. `Sprintf` formats // отформатированную строку в `os.Stdout`. `Sprintf`
// and returns a string without printing it anywhere. // форматирует и возвращает строку, нигде не печатая.
s := fmt.Sprintf("a %s", "string") s := fmt.Sprintf("a %s", "string")
fmt.Println(s) fmt.Println(s)
// You can format+print to `io.Writers` other than // Вы можете отформатировать+вывести в `io.Writers`, используя
// `os.Stdout` using `Fprintf`. // `Fprintf`.
fmt.Fprintf(os.Stderr, "an %s\n", "error") fmt.Fprintf(os.Stderr, "an %s\n", "error")
} }