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 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥15 微带串馈天线阵列每个阵元宽度计算