The new go.dev website makes the language Spec hard to find, which is 
unfortunate.

The spec is here -- it is one of the easiest language specs to read. 

https://go.dev/ref/spec

The section on the built-in (pre-declared) error interface is here

https://go.dev/ref/spec#Errors

Although struct values are allowed, they are very difficult to use 
correctly. I even
mess them up sometimes.

So until you get your feet with Go, I strongly recommend that you stick to 
only defining 
methods on pointers to structs, and passing around pointers to structs. 
Otherwise
you will likely shoot yourself in the foot by trying to update a value that 
cannot be
updated, and will wonder why your updates were lost.

To create a struct that implements the error
interface, you need to define all the methods in the error interface. 
Fortunately, there
is only one.

type error interface { 
 Error() string 
}

So your XError method could look look like this:

func (x *XError) Error() string {
   return fmt.Sprintf("XError: i = %v", x.i)
}

Then have methods return &XError{i: 99} or whatever you need.

func getAnError() error {
   return &XError{i: 99}
}

On Monday, August 18, 2025 at 5:28:44 PM UTC+1 andreas graeper wrote:

type XError struct { i int }

func f() (int,error) {
 return 0,XError{110} // bad-case 
 return 110,nil    // good-case
}

if r,e := f() ; e!=nil {
 println(e.i) // does not work 
 var xe XError 
 if errors.As(e,&xe) { println(xe.i) }
}

fun f() (int,XError) {
  return 0,XError{110}    // seems to work 
  return 123,nil // nil for XError is not possible 
}
if r,e = f() ; e!=nil { println( e.i ) } // ok

fun f() (int,*XError) {
  return 123,nil // this works 
}

type-interface (error) can be nil
type-struct (XError) cannot be nil, i need to replace with *XError ? 

is interface s.t like reference-type and struct a value-type ? 

thanks++, Andi 





-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
To view this discussion visit 
https://groups.google.com/d/msgid/golang-nuts/466c13eb-6881-4b7f-affe-84484793e297n%40googlegroups.com.

Reply via email to