Skip to content

Should a defensive copy of the tasks list be made? #54

@js-ojus

Description

@js-ojus

s.p.RUnlock()

The Go Language Reference document Section "Assignment statements" says:

"When a value is assigned to a variable, only the data that is stored in the variable is replaced. If the value contains a reference, the assignment copies the reference but does not make a copy of the referenced data (such as the underlying array of a slice)."

Would moving s.p.RUnlock() to after the loop be safer?

// GetTasks() returns a list of all tasks registered with the server.
func (s *Server) GetTasks() []string {
	s.p.RLock()
	tasks := s.tasks

	var (
		t = make([]string, len(tasks))
		i = 0
	)
	for k := range tasks {
		t[i] = k
		i++
	}
	s.p.RUnlock()

	return t
}

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