Untitled
unknown
plain_text
2 years ago
681 B
14
Indexable
package main
import (
"fmt"
"strings"
)
type lookupError struct {
src string
substr string
}
func (e lookupError) Error() string {
return fmt.Sprintf("'%s' not found in '%s'", e.substr, e.src)
}
func indexOf(src string, substr string) (int, error) {
idx := strings.Index(src, substr)
if idx == -1 {
// Создаем и возвращаем ошибку типа `lookupError`.
return -1, lookupError{src, substr}
}
return idx, nil
}
func main() {
src := "go is awesome"
_, err1 := indexOf(src, "js")
if err2, ok := err1.(lookupError); ok {
fmt.Println("err.src:", err2.src)
fmt.Println("err.substr:", err2.substr)
}
}
Editor is loading...
Leave a Comment