Standard library / sync

sync.Map.Swap()

Replace a value and return the previous value and presence flag. Expected stdout: '1 true\n'.

Formal Syntax & Structure

go syntaxgo
func (m *Map) Swap(key, value any) (previous any, loaded bool)

Parameters & Attributes

NameTypeDescription
keyanyComparable map key, or a package-specific comparable context key.
valueanyValue associated with the key.

Return Value

(previous any, loaded bool)

Previous value and whether it existed.

Working Example

Example Snippetgo
package main
import (  "fmt"  "sync")
func main() { var m sync.Map; m.Store("a", 1); v, ok := m.Swap("a", 2); fmt.Println(v, ok) }
Go Reference