pvd
pvd

Reputation: 1343

Go's sync.Map load result could not be added

I just wanted to do some simple CREATE or ADD on sync.Map

gore> :import sync
gore> var sm sync.Map
gore> sm.Store(12345,1)
gore> result, ok := sm.Load(12345)
1
true
gore> newr := result +1
# command-line-arguments
/var/folders/kl/n95_c8j15wn1784jmsq08mq80000gn/T/112740772/gore_session.go:21:17: invalid operation: result + 1 (mismatched types interface {} and int)
error: exit status 2
exit status 2

result is 1 on the repl ,but it couldn't be added with 1

Upvotes: 0

Views: 1116

Answers (1)

peterSO
peterSO

Reputation: 166744

The Go Programming Language Specification

Type assertions

For an expression x of interface type and a type T, the primary expression

x.(T)

asserts that x is not nil and that the value stored in x is of type T. The notation x.(T) is called a type assertion.


The error message tells all:

invalid operation: result + 1 (mismatched types interface {} and int)

Use a type assertion on result type interface {} for int:

package main

import (
    "fmt"
    "sync"
)

func main() {
    var sm sync.Map
    sm.Store(12345, 1)
    result, ok := sm.Load(12345)
    fmt.Println(result, ok)
    newr := result.(int) + 1
    fmt.Println(newr)
}

Playground: https://play.golang.org/p/qotBVR4fSNV

Output:

1 true
2

Upvotes: 1

Related Questions