Skip to content

单例模式中singleton结构体字段为空,多次赋值instance值是一样的 #30

@joengtou

Description

@joengtou

如下代码验证了空结构体多次赋值结果一样,在单例模式中golang-design-pattern/03_singleton/singleton.go line23,即使不用sync.Once 也能通过单元测试,应该给singleton添加一个字段

`package main

import (
"fmt"
)

var a1 *singleton1
var a2 *singleton2

type singleton1 struct {
}
type singleton2 struct {
d int
}

func getInstance1() *singleton1 {
a1 = &singleton1{}
return a1
}
func getInstance2() *singleton2 {
a2 = &singleton2{}
return a2
}
func main() {
b1, c1 := getInstance1(), getInstance1()
fmt.Println(b1 == c1)
//true
b2, c2 := getInstance2(), getInstance2()
fmt.Println(b2 == c2)
//false
}
`

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions