Re: [go-nuts] var errors stdlib

2024-05-10 Thread 'Dan Kortschak' via golang-nuts
On Fri, 2024-05-10 at 04:24 -0700, Sebastian Bogan wrote:
> Hello Everyone,
> 
> I was wondering, what was / is the reason for exposing errors as
> public vars - rather than constants? Doesn't that impose some risk?
> 
> For example:
> 
>   fs.ErrNotExist = errors.New("foo")
>   _, err = os.ReadFile("./invalid")
>   if !errors.Is(err, fs.ErrNotExist) {
>     fmt.Println("is NOT fs.ErrNotExist")
>   }
> 
> Would something like the following work (and be less risky)?:
> 
>   type ConstError string
>   func (e ConstError) Error() string {
>     return string(e)
>   }
>   const ErrNotExist = ConstError("file does not exist")
> 

Interface values cannot be consts per the spec. But to address the
concern, if some malicious or misguided package in your imports
reassigns a value to an exported error var, the example you show would
still work since the value is still common to all users of the var. If
the check were against the string returned by the Error method there
would be a problem, but that is advised against already. It could
potentially be a source of race conditions if the import made the
change after init and the read were happening in goroutine.

There are issues in the tracker that discuss const values,
https://go.dev/issue/6386 is probably a good place to start.

-- 
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 on the web visit 
https://groups.google.com/d/msgid/golang-nuts/c6794b216ee037e870621e650467fc0c6cb03437.camel%40kortschak.io.


[go-nuts] var errors stdlib

2024-05-10 Thread Sebastian Bogan
Hello Everyone,

I was wondering, what was / is the reason for exposing errors as public 
vars - rather than constants? Doesn't that impose some risk?

For example:

  fs.ErrNotExist = errors.New("foo")
  _, err = os.ReadFile("./invalid")
  if !errors.Is(err, fs.ErrNotExist) {
fmt.Println("is NOT fs.ErrNotExist")
  }

Would something like the following work (and be less risky)?:

  type ConstError string
  func (e ConstError) Error() string {
return string(e)
  }
  const ErrNotExist = ConstError("file does not exist")

Thanks
Seb

-- 
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 on the web visit 
https://groups.google.com/d/msgid/golang-nuts/45805816-9264-4312-a524-3fba6e3a77d2n%40googlegroups.com.