Skip to content

go/build: Why is replacing the map key not working as expected? #76805

@shuqingzai

Description

@shuqingzai

Go version

go version go1.25.4 darwin/amd64

Output of go env in your module/workspace:

#╰─⠠⠵ go env
AR='ar'
CC='clang'
CGO_CFLAGS='-O2 -g'
CGO_CPPFLAGS=''
CGO_CXXFLAGS='-O2 -g'
CGO_ENABLED='0'
CGO_FFLAGS='-O2 -g'
CGO_LDFLAGS='-O2 -g'
CXX='clang++'
GCCGO='gccgo'
GO111MODULE='on'
GOAMD64='v1'
GOARCH='amd64'
GOAUTH='netrc'
GOBIN='/Users/worker/Code/go/bin'
GOCACHE='/Users/worker/Library/Caches/go-build'
GOCACHEPROG=''
GODEBUG=''
GOENV='/Users/worker/Library/Application Support/go/env'
GOEXE=''
GOEXPERIMENT=''
GOFIPS140='off'
GOFLAGS=''
GOGCCFLAGS='-fPIC -arch x86_64 -m64 -fno-caret-diagnostics -Qunused-arguments -fmessage-length=0 -ffile-prefix-map=/var/folders/cf/29v27s5s3vb8_c62bstsjqnm0000gp/T/go-build3803336973=/tmp/go-build -gno-record-gcc-switches -fno-common'
GOHOSTARCH='amd64'
GOHOSTOS='darwin'
GOINSECURE=''
GOMOD='/Users/worker/Code/go-project/worker/stickercube-goframe/go.mod'
GOMODCACHE='/Users/worker/Code/go/pkg/mod'
GONOPROXY=''
GONOSUMDB=''
GOOS='darwin'
GOPATH='/Users/worker/Code/go'
GOPRIVATE=''
GOPROXY='https://goproxy.cn,https://goproxy.io,direct'
GOROOT='/usr/local/go'
GOSUMDB='sum.golang.org'
GOTELEMETRY='local'
GOTELEMETRYDIR='/Users/worker/Library/Application Support/go/telemetry'
GOTMPDIR=''
GOTOOLCHAIN='auto'
GOTOOLDIR='/usr/local/go/pkg/tool/darwin_amd64'
GOVCS=''
GOVERSION='go1.25.4'
GOWORK=''
PKG_CONFIG='pkg-config'

What did you do?

source code

package main

import (
	"fmt"
)

func main() {
	m1 := map[string]string{
		"a1": "aa",
		"b1": "bb",
	}
	m2 := make(map[string]string, len(m1))
	for k, v := range m1 {
		m2[k] = v+v
	}

	// replace m1 key with m2 value
	for k, v := range m1 {
		m1[m2[k]] = v
		delete(m1, k)
	}
	fmt.Println(m1)
	// output:
	//
	// map[aaaa:aa bbbb:bb] -- This is the expected output
	// map[:aa bbbb:bb] -- This is the actual output
}

What did you see happen?

This is the expected output

map[aaaa:aa bbbb:bb]

What did you expect to see?

This is the actual output

map[:aa bbbb:bb]

I'm sorry, I don't know much about the underlying mechanism of map. Is this as expected?

Metadata

Metadata

Assignees

No one assigned

    Labels

    QuestionIssues that are questions about using Go.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions