How to get the pointer of return value from function call?

后端 未结 3 2017
有刺的猬
有刺的猬 2020-11-27 18:09

I just need a pointer to time.Time, so the code below seems invalid:

./c.go:5: cannot take the address of time.Now()

I just wond

3条回答
  •  -上瘾入骨i
    2020-11-27 18:37

    You can't directly take the address of a function call (or more precisely the return value(s) of the function) as described by hobbs.

    There is another way but it is ugly:

    p := &[]time.Time{time.Now()}[0]
    fmt.Printf("%T %p\n%v", p, p, *p)
    

    Output (Go Playground):

    *time.Time 0x10438180
    2009-11-10 23:00:00 +0000 UTC
    

    What happens here is a struct is created with a literal, containing one element (the return value of time.Now()), the slice is indexed (0th element) and the address of the 0th element is taken.

    So rather just use a local variable:

    t := time.Now()
    p := &t
    

    Or a helper function:

    func ptr(t time.Time) *time.Time {
        return &t
    }
    
    p := ptr(time.Now())
    

    Which can also be a one-liner anonymous function:

    p := func() *time.Time { t := time.Now(); return &t }()
    

    Or as an alternative:

    p := func(t time.Time) *time.Time { return &t }(time.Now())
    

    For even more alternatives, see:

    How do I do a literal *int64 in Go?

    Also see related question: How can I store reference to the result of an operation in Go?

提交回复
热议问题