douxi8119 2013-05-25 13:42
浏览 37
已采纳

为什么这个匿名函数返回相同的struct实例?

package main

import "fmt"

type fake struct {
}

func main() {
    f := func() interface{} {
        return &fake{}
    }

    one := f()
    two := f()

    fmt.Println("Are equal?: ", one == two)
    fmt.Printf("%p", one)
    fmt.Println()
    fmt.Printf("%p", two)
    fmt.Println()
}

(http://play.golang.org/p/wxCUUCyz98)

Why does this anonymous func return the same instance of the requested type and how can i make it return a new one on each call?

  • 写回答

2条回答 默认 最新

  • doujiao8491 2013-05-25 13:53
    关注

    You compare two interfaces with one == two. Let's see what the language specification has to say on the meaning of this expression:

    Interface values are comparable. Two interface values are equal if they have identical dynamic types and equal dynamic values or if both have value nil.

    Pointer values are comparable. Two pointer values are equal if they point to the same variable or if both have value nil. Pointers to distinct zero-size variables may or may not be equal.

    In your example, both one and two are both interface values, and they have the same dynamic type (*fake). Their dynamic values are both pointers to a zero-sized object though, and as you can read above, equality may or may not hold in this case.

    Given this, you can solve your problem by not using pointers to zero-sized structs as unique values. Perhaps use an int instead?

    That might look like this:

    type fake int
    
    func main() {
        var uniq fake
        f := func() interface{} {
            uniq++
            return uniq
        }
        ...
    }
    

    It's not clear what you're trying to achieve, so this may or may not be a good solution for you.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题
  • ¥20 yolov5自定义Prune报错,如何解决?