#How do I make errors?
34 messages · Page 1 of 1 (latest)
error is an interface, so you can return any type that has a method of Error() string on it. that said, there are some helper functions that exist to easily create one, like errors.New or fmt.Errorf, that take in a string and return a value that already has that method implemented for you
if you want to take an existing error and add more context to it, you can "wrap" it with the %w verb on fmt.Errorf. this allows the consumer of the error to both have that new context but also retrieve the inner error by unwrapping it
Uh, as a bit of a newbie, I'm not sure I fully understand what an interface is.
an interface is just a set of methods, and any type that implements all of those methods is said to implement (or satisfy) the interface. then, you can use that type wherever the interface type is expected
the definition of error is:
type error interface {
Error() string
}
meaning that any type that has a method with the signature Error() string satisfies error, and any value of one of those types can be used wherever an error is wanted
notice how a can take refer to values of different types, because they both implement the Abser interface
at first it refers to a MyFloat, then it refers to a *Vertex
no, Abser is an interface
And MyFloat and *Vertex implement Abser why?
we'd say they implement Abser, not that they are implemented by it
sure
they both have an Abs() float64 method, see lines 29 and 40
if you look at the definition of Abser, that is precisely what is required to implement Abser
ohhh. That makes a lot of sense
So why have Abser and not just Abs?
why not have a be a float64?
because there are multiple types of mathematical constructs that have the absolute value operation defined on them
one is a float, but another is a vertex
having Abser allows logic using an absolute value to be written only once for both types (and even more types)
I think I have a ton to learn lol. Is there a master guide to how Go works? I've tried the Go tour but I didn't really learn much from it.
the tour is the canonical set of resources for beginners. i would suggest going through it again and identifying where you feel like there's a gap in knowledge before moving on, and if you're not able to put things together i'm sure anyone around here would be happy to help
it's easy to just go to the next page when something doesn't make much sense, but try to resist that