mirror of
https://github.com/Pungyeon/clean-go-article.git
synced 2024-11-23 06:04:05 +00:00
update readme, fix formatting
This commit is contained in:
parent
3011efee29
commit
7e2ba16f20
20
README.md
20
README.md
|
@ -814,27 +814,27 @@ There are other scenarios in which it is common to find `nil` values that can ca
|
||||||
|
|
||||||
```go
|
```go
|
||||||
type App struct {
|
type App struct {
|
||||||
Cache *KVCache
|
Cache *KVCache
|
||||||
}
|
}
|
||||||
|
|
||||||
type KVCache struct {
|
type KVCache struct {
|
||||||
mtx sync.RWMutex
|
mtx sync.RWMutex
|
||||||
store map[string]string
|
store map[string]string
|
||||||
}
|
}
|
||||||
|
|
||||||
func (cache *KVCache) Add(key, value string) {
|
func (cache *KVCache) Add(key, value string) {
|
||||||
cache.mtx.Lock()
|
cache.mtx.Lock()
|
||||||
defer cache.mtx.Unlock()
|
defer cache.mtx.Unlock()
|
||||||
|
|
||||||
cache.store[key] = value
|
cache.store[key] = value
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
This code is absolutely fine. However, the danger is that our `App` can be initialised incorrectly, without initialising the `Cache` property within. Should the following code be invoked, our application will panic:
|
This code is absolutely fine. However, the danger is that our `App` can be initialised incorrectly, without initialising the `Cache` property within. Should the following code be invoked, our application will panic:
|
||||||
|
|
||||||
```go
|
```go
|
||||||
app := App{}
|
app := App{}
|
||||||
app.Cache.Add("panic", "now")
|
app.Cache.Add("panic", "now")
|
||||||
```
|
```
|
||||||
|
|
||||||
The `Cache` property has never been initialised and is therefore a `nil` pointer. Thus, invoking the `Add` method like we did here will cause a panic, with the following message:
|
The `Cache` property has never been initialised and is therefore a `nil` pointer. Thus, invoking the `Add` method like we did here will cause a panic, with the following message:
|
||||||
|
@ -845,14 +845,14 @@ Instead, we can turn the `Cache` property of our `App` structure into a private
|
||||||
|
|
||||||
```go
|
```go
|
||||||
type App struct {
|
type App struct {
|
||||||
cache *KVCache
|
cache *KVCache
|
||||||
}
|
}
|
||||||
|
|
||||||
func (app *App) Cache() *KVCache {
|
func (app *App) Cache() *KVCache {
|
||||||
if app.cache == nil {
|
if app.cache == nil {
|
||||||
app.cache = NewKVCache()
|
app.cache = NewKVCache()
|
||||||
}
|
}
|
||||||
return app.cache
|
return app.cache
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
|
Loading…
Reference in a new issue