Untitled

mail@pastecode.io avatar
unknown
plain_text
a month ago
681 B
8
Indexable
Never
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)
	}
}
Leave a Comment