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

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 ? 


interfaces are like boxes, containing a <concrete-type, ref-to-value> 
pair.  A nil interface is effectively <nil, nil>  - no type and therefore 
no value.

A nil interface is not the same as a nil pointer.  Hence, an interface 
containing any concrete value of type *foo (even if that value is nil) is 
not a nil interface value.
https://go.dev/play/p/-RMIHaJmbno

And if your function returned a *XError type, even if it returned a nil 
pointer, but the caller assigned it to a variable which holds an "error" 
type (which is an interface), this would show as a not-nil interface value.
https://go.dev/play/p/kL8jYHuLBnA

The normal rule in Go is "return concrete types, accept interfaces". This 
gives maximum flexibility and type safety. However, errors are a special 
case: conventionally you return a value of interface type "error". In that 
case, a nil (interface) value means "no error" and any other value means 
"some error". Since it's an interface, you know that any non-nil value 
implements the Error() method.

Therefore, you did the right thing here:

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

although a separate convention is that it's recommended that error values 
are pointers - this was discussed recently on this group.

-- 
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/0d62279e-a38e-4ebd-830f-028f14e2923dn%40googlegroups.com.

Reply via email to