diff --git a/examples.txt b/examples.txt index 365237b..1fdaa6e 100644 --- a/examples.txt +++ b/examples.txt @@ -18,7 +18,7 @@ Switch Структуры (Structs) Методы (Methods) Интерфейсы (Interfaces) -Errors +Ошибки (Errors) Goroutines Channels Channel Buffering diff --git a/examples/errors/errors.go b/examples/errors/errors.go index b850139..1876ae4 100644 --- a/examples/errors/errors.go +++ b/examples/errors/errors.go @@ -1,11 +1,11 @@ -// In Go it's idiomatic to communicate errors via an -// explicit, separate return value. This contrasts with -// the exceptions used in languages like Java and Ruby and -// the overloaded single result / error value sometimes -// used in C. Go's approach makes it easy to see which -// functions return errors and to handle them using the -// same language constructs employed for any other, -// non-error tasks. +// В Go принято сообщать об ошибках через явное, отдельное +// возвращаемое значение. Это контрастирует с исключениями, +// используемыми в таких языках, как Java и Ruby, и +// перегруженным одиночным значением результата/ошибки, +// иногда используемым в подходе C. Go, позволяет легко +// увидеть, какие функции возвращают ошибки, и обрабатывать +// их, используя те же языковые конструкции, которые +// используются для любых других задач без ошибок. package main @@ -14,26 +14,26 @@ import ( "fmt" ) -// By convention, errors are the last return value and -// have type `error`, a built-in interface. +// По соглашению, ошибки - это последнее возвращаемое +// значение с типом `error` в стандартной реализации. func f1(arg int) (int, error) { if arg == 42 { - // `errors.New` constructs a basic `error` value - // with the given error message. + // `errors.New` создает стандартную `ошибку` с + // указаннным сообщением return -1, errors.New("can't work with 42") } - // A `nil` value in the error position indicates that - // there was no error. + // Значение `nil` в поле ошибки, говорит о том, что + // ошибок нет. return arg + 3, nil } -// It's possible to use custom types as `error`s by -// implementing the `Error()` method on them. Here's a -// variant on the example above that uses a custom type -// to explicitly represent an argument error. +// Можно использовать пользовательские типы в качестве +// ошибок, применяя к ним метод `Error()`. Вот вариант +// в примере выше, который использует пользовательский +// тип для явного представления ошибки аргумента. type argError struct { arg int prob string @@ -46,9 +46,9 @@ func (e *argError) Error() string { func f2(arg int) (int, error) { if arg == 42 { - // In this case we use `&argError` syntax to build - // a new struct, supplying values for the two - // fields `arg` and `prob`. + // В этом случае мы используем синтаксис `&argError` + // для создания новой структуры, предоставляя + // значения для двух полей `arg` и `prob`. return -1, &argError{arg, "can't work with it"} } return arg + 3, nil @@ -56,10 +56,10 @@ func f2(arg int) (int, error) { func main() { - // The two loops below test out each of our - // error-returning functions. Note that the use of an - // inline error check on the `if` line is a common - // idiom in Go code. + // Два цикла ниже тестируют каждую из наших функций, + // возвращающих ошибки. Обратите внимание, что + // использование встроенной проверки ошибок в строке + // `if` является обычный явлением в Go. for _, i := range []int{7, 42} { if r, e := f1(i); e != nil { fmt.Println("f1 failed:", e) @@ -75,10 +75,9 @@ func main() { } } - // If you want to programmatically use the data in - // a custom error, you'll need to get the error as an - // instance of the custom error type via type - // assertion. + // Если вы хотите использовать данные в пользовательской + // ошибке, вам нужно получить ошибку как экземпляр + // пользовательского типа через утверждение типа. _, e := f2(42) if ae, ok := e.(*argError); ok { fmt.Println(ae.arg) diff --git a/examples/errors/errors.sh b/examples/errors/errors.sh index 068d606..16d6ce1 100644 --- a/examples/errors/errors.sh +++ b/examples/errors/errors.sh @@ -6,5 +6,5 @@ f2 failed: 42 - can't work with it 42 can't work with it -# See this [great post](http://blog.golang.org/2011/07/error-handling-and-go.html) -# on the Go blog for more on error handling. +# Посмотрите [эту статью](http://blog.golang.org/2011/07/error-handling-and-go.html) +# в блоге Go для более подробной информации об ошибках.