подпрограммы

This commit is contained in:
badkaktus 2019-10-12 21:08:18 +03:00
parent e62cee4774
commit 89b09c204a
3 changed files with 23 additions and 23 deletions

View File

@ -64,7 +64,7 @@ Epoch
Тестирование (Testing)
Аргументы командной строки (Command-Line Arguments)
Флаги командной строки (Command-Line Flags)
Command-Line Subcommands
Подкоманды командной строки (Command-Line Subcommands)
Environment Variables
HTTP Clients
HTTP Servers

View File

@ -1,9 +1,9 @@
// Some command-line tools, like the `go` tool or `git`
// have many *subcommands*, each with its own set of
// flags. For example, `go build` and `go get` are two
// different subcommands of the `go` tool.
// The `flag` package lets us easily define simple
// subcommands that have their own flags.
// Некоторые инструменты командной строки, такие как `go`
// или `git`, имеют много *подкоманд*, каждая со своим
// собственным набором флагов. Например, `go build` и
// `go get` - это две разные подкоманды инструмента `go`.
// Пакет `flag` позволяет нам легко определять простые
// подкоманды, которые имеют свои собственные флаги.
package main
@ -15,30 +15,30 @@ import (
func main() {
// We declare a subcommand using the `NewFlagSet`
// function, and proceed to define new flags specific
// for this subcommand.
// Мы объявляем подкоманду, используя функцию `NewFlagSet`,
// и приступаем к определению новых флагов, специфичных
// для этой подкоманды.
fooCmd := flag.NewFlagSet("foo", flag.ExitOnError)
fooEnable := fooCmd.Bool("enable", false, "enable")
fooName := fooCmd.String("name", "", "name")
// For a different subcommand we can define different
// supported flags.
// Для другой подкоманды мы можем определить другие
// флаги.
barCmd := flag.NewFlagSet("bar", flag.ExitOnError)
barLevel := barCmd.Int("level", 0, "level")
// The subcommand is expected as the first argument
// to the program.
// Подкоманда ожидается в качестве первого аргумента
// программы.
if len(os.Args) < 2 {
fmt.Println("expected 'foo' or 'bar' subcommands")
os.Exit(1)
}
// Check which subcommand is invoked.
// Проверяем, какая подкоманда вызвана.
switch os.Args[1] {
// For every subcommand, we parse its own flags and
// have access to trailing positional arguments.
// Для каждой подкоманды мы анализируем ее собственные
// флаги и имеем доступ к аргументам.
case "foo":
fooCmd.Parse(os.Args[2:])
fmt.Println("subcommand 'foo'")

View File

@ -1,24 +1,24 @@
$ go build command-line-subcommands.go
$ go build command-line-subcommands.go
# First invoke the foo subcommand.
# Первый вызов подкоманды foo.
$ ./command-line-subcommands foo -enable -name=joe a1 a2
subcommand 'foo'
enable: true
name: joe
tail: [a1 a2]
# Now try bar.
# Теперь пробуем bar.
$ ./command-line-subcommands bar -level 8 a1
subcommand 'bar'
level: 8
tail: [a1]
# But bar won't accept foo's flags.
# Но bar не может принимать флаги определенные для foo.
$ ./command-line-subcommands bar -enable a1
flag provided but not defined: -enable
Usage of bar:
-level int
level
# Next we'll look at environment variables, another common
# way to parameterize programs.
# Далее мы рассмотрим переменные окружения, еще один
# распространенный способ параметризации программ.