Well here is the code that works as I need, what is wrong with the previous
one ?
https://go.dev/play/p/ZW-GmEP5uqu

package main

import (
"fmt"
)

type process struct {
}

func (p *process) close(err any) {
v, _ := err.(*int)
if *v == 1 {
fmt.Println("error")
} else {
fmt.Println("no error")
}
}
func Handle(b bool) {
p := process{}
var i = 2
var pt any = &i
defer func() {
p.close(pt)
}()
if b {
i = 1
}
}

func HandleWTF(b bool) {
p := process{}
var i = 2
var pt any = &i
defer p.close(pt)
if b {
i = 1
}
}

func main() {
Handle(true)    // error
Handle(false)   // no error
HandleWTF(true) // error
}


On Sat, Aug 26, 2023 at 6:10 PM Brian Candler <b.cand...@pobox.com> wrote:

> Any arguments to defer functions are evaluated at the time that the defer
> is executed.  In HandleWTF, defer p.close(err) is called immediately after
> err is declared with value nil, so nil is what is used.
>
> From the specification <https://go.dev/ref/spec#Defer_statements>:
>
> "Each time a "defer" statement executes, the function value and
> parameters to the call are evaluated as usual
> <https://go.dev/ref/spec#Calls> and saved anew but the actual function is
> not invoked."
>
> On Saturday, 26 August 2023 at 15:58:06 UTC+1 Aln Kapa wrote:
>
>> Hi All !
>> Need some help, what am I doing wrong?
>>
>> https://go.dev/play/p/bBlA-i1CxNO
>>
>> // You can edit this code!
>> // Click here and start typing.
>> package main
>>
>> import (
>> "errors"
>> "fmt"
>> )
>>
>> type process struct {
>> }
>>
>> func (p *process) close(err error) {
>> if err != nil {
>> fmt.Println("error")
>> } else {
>> fmt.Println("no error")
>> }
>> }
>> func Handle(b bool) {
>> p := process{}
>> var err error
>> defer func() {
>> p.close(err)
>> }()
>> if b {
>> err = errors.New("err")
>> }
>> }
>>
>> func HandleWTF(b bool) {
>> p := process{}
>> var err error
>> defer p.close(err)
>> if b {
>> err = errors.New("err")
>> }
>> }
>>
>> func main() {
>> Handle(true)    // error
>> Handle(false)   // no error
>> HandleWTF(true) // no error ?????????
>> }
>>
> --
> 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/25846715-b3bf-4d1d-81b4-4a2799e69d27n%40googlegroups.com
> <https://groups.google.com/d/msgid/golang-nuts/25846715-b3bf-4d1d-81b4-4a2799e69d27n%40googlegroups.com?utm_medium=email&utm_source=footer>
> .
>

-- 
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/CAJqqVEUE4M0Hn%3DeRi2HPePCETXwRMxqxMifpquhOp18cifgXJQ%40mail.gmail.com.

Reply via email to