การรับคำสั่ง Slices และ Maps
โปรดจำไว้ว่าเมื่อ map หรือ slice ถูกส่งเป็นพารามิเตอร์ของฟังก์ชัน หากคุณเก็บ reference ไว้ ผู้ใช้สามารถแก้ไขข้อมูลนั้นได้
การเข้าถึงที่ไม่แนะนำ:
func (d *Driver) SetTrips(trips []Trip) {
d.trips = trips
}
trips := ...
d1.SetTrips(trips)
// คุณพยายามแก้ไข d1.trips ใช่ไหม?
trips[0] = ...
การเข้าถึงที่แนะนำ:
func (d *Driver) SetTrips(trips []Trip) {
d.trips = make([]Trip, len(trips))
copy(d.trips, trips)
}
trips := ...
d1.SetTrips(trips)
// ที่นี่เราแก้ไข trips[0] แต่มันจะไม่มีผลต่อ d1.trips
trips[0] = ...
การส่งคืน Slices หรือ Maps
เช่นเดียวกัน โปรดระมัดระวังถึงการแก้ไข map หรือ slice ที่เปิดเผยสถานะภายใน
การเข้าถึงที่ไม่แนะนำ:
type Stats struct {
mu sync.Mutex
counters map[string]int
}
// Snapshot ส่งคืนสถานะปัจจุบัน
func (s *Stats) Snapshot() map[string]int {
s.mu.Lock()
defer s.mu.Unlock()
return s.counters
}
// การเข้าถึง snapshot ไม่ได้รับการคุ้มครองโดย mutex แล้ว
// ดังนั้นการเข้าถึง snapshot จะมีโอกาสทำให้เกิดการแข่งขันข้อมูลและมีผลต่อ stats.counters
snapshot := stats.Snapshot()
การเข้าถึงที่แนะนำ:
type Stats struct {
mu sync.Mutex
counters map[string]int
}
func (s *Stats) Snapshot() map[string]int {
s.mu.Lock()
defer s.mu.Unlock()
result := make(map[string]int, len(s.counters))
for k, v := range s.counters {
result[k] = v
}
return result
}
// ตอนนี้ snapshot เป็นการคัดลอก
snapshot := stats.Snapshot()